Leetcode 504 题
Difficulty:Easy
Tag: Math
Base 7
题目原址:https://leetcode.com/problems/base-7/?tab=Description
Given an integer, return its base 7 string representation.
思路
进制转换,基数为 7,短除法
代码
很直接,结果是余数的逆序,可以选择栈来存储,亦可以选择string存储,最后输出string翻转的结果。
class Solution {
public:
string convertToBase7(int num) {
if(num == 0) return "0";
int a = num > 0 ? num : -num;
int b;
stack<int> sk;
while(a != 0)
{
b = a % 7;
a = a / 7;
sk.push(b);
}
string res;
while(!sk.empty())
{
res += to_string(sk.top());
sk.pop();
}
return num > 0 ? res : "-" + res;
}
};