Welcome to Subscribe On Youtube

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:
        def convertToBase7(self, num: int) -> str:
            if num == 0:
                return '0'
            if num < 0:
                return '-' + self.convertToBase7(-num)
            ans = []
            while num:
                ans.append(str(num % 7))
                num //= 7
            return ''.join(ans[::-1])
    
    ############
    
    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)
    
    
  • func convertToBase7(num int) string {
    	if num == 0 {
    		return "0"
    	}
    	if num < 0 {
    		return "-" + convertToBase7(-num)
    	}
    	ans := []byte{}
    	for num != 0 {
    		ans = append([]byte{'0' + byte(num%7)}, ans...)
    		num /= 7
    	}
    	return string(ans)
    }
    
  • function convertToBase7(num: number): string {
        if (num == 0) {
            return '0';
        }
        let res = '';
        const isMinus = num < 0;
        if (isMinus) {
            num = -num;
        }
        while (num != 0) {
            const r = num % 7;
            res = r + res;
            num = (num - r) / 7;
        }
        return isMinus ? '-' + res : res;
    }
    
    
  • impl Solution {
        pub fn convert_to_base7(mut num: i32) -> String {
            if num == 0 {
                return String::from("0");
            }
            let mut res = String::new();
            let is_minus = num < 0;
            if is_minus {
                num = -num;
            }
            while num != 0 {
                res.push_str((num % 7).to_string().as_str());
                num /= 7;
            }
            if is_minus {
                res.push('-');
            }
            res.chars().rev().collect()
        }
    }
    
    

All Problems

All Solutions