LeetCode : Base 7

来源:互联网 发布:公积金贷款的软件 编辑:程序博客网 时间:2024/06/04 19:14

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].

class Solution {public:    string convertToBase7(int num) {        vector<int>res;        string dst="";        if(num==0)             return "0";        if(num<0)           {               dst+="-";               num = -num;           }        while(num)        {            res.push_back(num%7);            num/=7;        }       // stringstream ss;        int i = 0;        string temp = "";        reverse(res.begin(),res.end());        while(i<res.size())        {            stringstream ss;//stringstream每次只能读取一遍,下一次需要清                      空,所以这里就定义局部变量            ss<<res[i];            ss>>temp;            dst+=temp;            ++i;        }        return dst;    }};
0 0
原创粉丝点击