[LeetCode] 504. Base 7 ❤

来源:互联网 发布:js笔试题及答案 编辑:程序博客网 时间:2024/06/05 16:19

Given an integer, return its base 7 string representation.

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

_____________________________________________ 以上题目

十进制转n进制的题目,思路相同。加了一个判断正负,加了一个reverse字符串。完成

class Solution {public:    string convertToBase7(int num) {        string ret;        int shang, yushu;        shang = abs(num) / 7;        yushu = abs(num) % 7;        while (shang != 0) {            ret += yushu + '0';            yushu = shang % 7;            shang /= 7;        }        ret += yushu + '0';        reverse(ret.begin(), ret.end());        if (num < 0) ret.insert(ret.begin(), '-');        return ret;    }};


原创粉丝点击