Leetcode 504 Base 7

HowieLee59發表於2018-12-12

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餘下的數的串,程式中需要考慮為空值和負數的時候。

1)

class Solution {
public:
    string convertToBase7(int num) {
        string res;
        bool is_neg = false;
        if(num < 0){
            num *= -1;
            is_neg = true;
        }else if(!num){
            res += '0';
        }
        while(num != 0){
            res += to_string(num % 7);
            num /= 7;
        }
        if(is_neg){
            res += "-";
        }
        return string(res.rbegin(),res.rend());
    }
};

相關文章