您的位置:首页 > 其它

leetcode 504. Base 7(easy)

2017-04-20 10:20 393 查看
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].

题目是要将10进制转换成7进制,但是需要注意这里是转换成string,同时需要注意负数和0的处理。

class Solution {
public:
string convertToBase7(int num) {
//转换成7机制,那么就连续除以7
string result;
if(num == 0) {result = '0'; return result;}
int flag = 0;
if(num<0)
{
num = -num;
flag = 1;
}
while(num != 0)
{
int a = num%7;
num = num/7;
stringstream ss;
ss<<a;
result = ss.str() + result;
}
if(flag == 1) result = "-"+result;
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: