Blog Details

Base 7

1. Description

Given an integer, return its base 7 string representation.

2. Example

Input: 100
Output: 202

Input: -7
Output: -10

3. Solution

class Solution {
    public String convertToBase7(int num) {
        StringBuffer sb = new StringBuffer();
        int absNum = Math.abs(num);
        if(absNum < 7) { return num + "";}
        while(true) {
            int remaining = absNum % 7;
            absNum = absNum / 7;
            sb.insert(0, remaining);
            if(absNum < 7) {
                sb.insert(0, absNum);
                break;
            }
        }
        return num < 0 ? sb.insert(0, "-").toString() : sb.toString();
    }
}

4. Complexity

Time: O(n)

Space: O(1)