504. Base 7

QUESTION:

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].

EXPLANATION:

其实就是7进制的换算,然后Integer中是有对应的api的,leetcode中也是没有办法判断的,但是效率都不是很高。

SOLUTION

   public String convertToBase7(int num) {
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        if(Math.abs(num)!=num){
            flag = true;
            num = Math.abs(num);
        }
        int index = -1;
        int remain = 0;
        while (index != 0) {
            index = num/7;
            remain = num%7;
            sb.insert(0, remain + "");
            num = num/7;
        }
        if(flag)
            sb.insert(0,"-");
        return sb.toString();
    }