504. 七进制数

给定一个整数,将其转化为7进制,并以字符串形式输出。

示例 1:

输入: 100
输出: "202"
示例 2:

输入: -7
输出: "-10"
注意: 输入范围是 [-1e7, 1e7] 。

 

class Solution {
public:
    string convertToBase7(int num) {
        if (num == 0) return "0";
        if (num < 0) return "-" + convertToBase7(-num);
        return (num >= 7 ? convertToBase7(num / 7) : "") + (char)(48 + num % 7);
    }
};

 

 

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

 

 

 

class Solution {
public:
    string convertToBase7(int num) {
        if (num == 0) return "0";
        string res = "";
        string sgn = "";
        if (num < 0) {
            num = -num;
            sgn = "-";
        }
        while (num > 0) {
            res.push_back(48 + num % 7);
            num /= 7;
        }
        std::reverse(begin(res), end(res));
        return sgn + res;
    }
};

 

posted @ 2020-10-04 20:01  XXXSANS  阅读(207)  评论(0编辑  收藏  举报