504 Base 7 Heptadecimal

Given an integer, convert it to base 7 and output it as a string.
Example 1:
Input: 100
Output: "202"

Example 2:
Input: -7
Output: "-10"
Note: The input range is [-1e7, 1e7].
See: https://leetcode.com/problems/base-7/description/

C++:

class Solution {
public:
    string convertToBase7(int num) {
        if(num==0)
        {
            return "0";
        }
        string res="";
        bool positive=num>0;
        while(num!=0)
        {
            res=to_string(abs(num%7))+res;
            num/=7;
        }
        return positive?res:"-"+res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324620978&siteId=291194637