Formatted question description: https://leetcode.ca/all/504.html

504. Base 7

Level

Easy

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

If nums is 0, simply return “0”.

Otherwise, split the sign out and deal with the absolute value of num. Each time divide num by 7 and store the remainders in the reverse order until num becomes 0. If num is negative initially, add the negative sign. Finally return the string of base 7 representation.

class Solution {
    public String convertToBase7(int num) {
        if (num == 0)
            return "0";
        int sign = num >= 0 ? 1 : -1;
        num = Math.abs(num);
        StringBuffer base7 = new StringBuffer();
        while (num > 0) {
            int remainder = num % 7;
            base7.insert(0, (char) (remainder + '0'));
            num /= 7;
        }
        if (sign < 0)
            base7.insert(0, '-');
        return base7.toString();
    }
}

All Problems

All Solutions