[LeetCode] Base 7

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]

题目要求将十进制转换成七进制,如果数字是0则直接返回字符串“0”,如果数字是负数,需要在把它变成正数后再转换。在转换结束后添加“-”号后反转字符串即可。

class Solution {
public:
    string convertToBase7(int num) {
        if (num == 0)
            return "0";
        string s;
        bool isPos = true;
        int tmp = 0;
        if (num < 0) {
            isPos = false;
            num = -num;
        }
        while (num > 0) {
            tmp = num % 7;
            s += to_string(tmp);
            num /= 7;
        }
        if (!isPos)
            s += "-";
        reverse(s.begin(), s.end());
        return s;
    }
};
// 6 ms

 

posted @ 2017-07-18 14:46  immjc  阅读(164)  评论(0编辑  收藏  举报