给定整数,转换为7进制字符串,这里美中不足的是针对数字0需要特殊处理,递归条件里无法区分0这种情况。

class Solution {
public:
    string convertToBase7(int num) {
        if(num == 0) return "0";
        string res;
        if(num < 0)
        {
            res+='-';
            num = -1 * num;
        }
        helper(res,num);
        return res;
    }
private:
    void helper(string& res,int num) {
        if(num == 0) return;
        helper(res,num/7);
        res += '0' + num%7;
    }
};

运行效率:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Base 7.
Memory Usage: 6 MB, less than 51.74% of C++ online submissions for Base 7.

看了一眼评论区大家的代码都是用的do while结构,恍然大悟,至少执行一次,do while可以解决。

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

运行效率:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Base 7.
Memory Usage: 6 MB, less than 51.74% of C++ online submissions for Base 7.

代码看上去简洁多了,又不用进行特殊处理。