LeetCode 504: Base 7 Solution

Master LeetCode problem 504 (Base 7), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

504. Base 7

Easy

Problem Explanation

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.

Solution Code

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();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 504 (Base 7)?

This page provides optimized solutions for LeetCode problem 504 (Base 7) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 504 (Base 7)?

The time complexity for LeetCode 504 (Base 7) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 504 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 504 in Java, C++, or Python.

Back to LeetCode Solutions