Skip to content

Latest commit

 

History

History

504

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given an integer num, return a string of its base 7 representation.

 

Example 1:

Input: num = 100
Output: "202"

Example 2:

Input: num = -7
Output: "-10"

 

Constraints:

  • -107 <= num <= 107

Companies:
Google

Related Topics:
Math

Solution 1.

// OJ: https://leetcode.com/problems/base-7/
// Author: github.com/lzl124631x
// 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;
    }
};