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();
        }
    }
    
  • // OJ: https://leetcode.com/problems/base-7/
    // Time: O(logN)
    // Space: O(logN)
    class Solution {
    public:
        string convertToBase7(int n) {
            if (n == 0) return "0";
            string ans;
            bool neg = false;
            if (n < 0) n = -n, neg = true;
            while (n) {
                ans += '0' + n % 7;
                n /= 7;
            }
            if (neg) ans += '-';
            reverse(begin(ans), end(ans));
            return ans;
        }
    };
    
  • class Solution(object):
      def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
    
        def convertHelper(num, base):
          sign = ""
          if num < 0:
            sign = "-"
          num = abs(num)
          ans = 0
          unit = 1
          while num:
            ans += (num % base) * unit
            num /= base
            unit *= 10
          return sign + str(ans)
    
        return convertHelper(num, 7)
    
    

All Problems

All Solutions