(Easy) Base 7 LeetCode

Description:

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

 

Example 2:

Input: -7
Output: "-10"

 

Note: The input will be in range of [-1e7, 1e7].

 

Solution:

class Solution {
    public String convertToBase7(int num) {
        if(num==0){
            return "0";
        }
        int dig = 0;
         String result = "";
        if(num>0){
        result = "";
        do {
            
            dig = num%7;
            num = num/7;
            
            result = result + dig;
            
            
        }   
        
            while (num>0);
                
                
        return Reverse(result);
                
        }
        else{
            
            num = -num;
            
               do {
            
            dig = num%7;
            num = num/7;
            
            result = result + dig;
            
            
        }   
        
            while (num>0);

    
        result = result+"-";
            return Reverse(result);
    }
    
}
    
    
    public String Reverse(String a ){
        
        StringBuffer sb = new StringBuffer(a);
        return sb.reverse().toString();
    }
}

 

posted @ 2019-08-12 17:51  CodingYM  阅读(155)  评论(0编辑  收藏  举报