LeetCode 504: Base 7

Math

Problem Description

Explanation

To convert an integer to its base 7 representation, we can repeatedly divide the number by 7 and keep track of the remainders. The remainders will form the base 7 representation in reverse order. If the input number is negative, we need to handle the sign separately.

  1. Handle the case when num is 0.
  2. Handle the sign of the number if it is negative.
  3. Iterate through the process of dividing the absolute value of num by 7 and storing the remainders.
  4. Construct the base 7 representation string by reversing the remainders and adding the sign if needed.

Time complexity: O(log n) where n is the absolute value of the input number. Space complexity: O(log n) to store the remainders.

Solutions

class Solution {
    public String convertToBase7(int num) {
        if (num == 0) {
            return "0";
        }
        
        StringBuilder result = new StringBuilder();
        boolean isNegative = num < 0;
        
        if (isNegative) {
            num = -num;
        }
        
        while (num > 0) {
            int remainder = num % 7;
            result.append(remainder);
            num /= 7;
        }
        
        if (isNegative) {
            result.append("-");
        }
        
        return result.reverse().toString();
    }
}

Loading editor...