题目:
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].
解释:
十进制转七进制,进制转换有自己的套路,只是对于负数,需要先求其绝对值,最后再把负号加上就好。
python代码:
class Solution:
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num==0:
return "0"
new_num=abs(num)
result=""
while new_num:
result=str(new_num%7)+result
new_num//=7
return result if num>0 else "-"+result
c++代码:
class Solution {
public:
string convertToBase7(int num) {
if (num==0)
return "0";
string result="";
int new_num=abs(num);
while(new_num)
{
result=to_string(new_num%7)+result;
new_num/=7;
}
return num>0?result:"-"+result;
}
};
总结:
进制转换的套路是固定的。