LeetCode 504. Base 7 (C++)

题目:

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].

分析:

给定一个7进制数,求十进制表示,注意返回的是字符串。

进制转换没什么好说的,注意这道题测试用例是有负数的,且返回值是字符串,记得转成字符串形式。

程序:

class Solution {
public:
    string convertToBase7(int num) {
        if(num == 0) return "0";
        string res;
        int n = abs(num);
        while(n){
            res = to_string(n%7) + res;
            n /= 7;
        }
        if(num < 0)
            return "-"+res;
        else
            return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/silentteller/p/10727169.html