LeetCode-504. Base 7https://leetcode.com/problems/base-7/
题目描述
Given an integer num
, return a string of its base 7 representation.
Example 1:
Input: num = 100 Output: "202"
Example 2:
Input: num = -7 Output: "-10"
Constraints:
-10^7 <= num <= 10^7
解题思路
【C++】
class Solution {
public:
string convertToBase7(int num) {
if (num == 0) {return "0";}
bool is_negative = num < 0;
if (is_negative) {num = -num;}
string ans;
while (num > 0) {
int a = num / 7, b = num % 7;
ans = to_string(b) + ans;
num = a;
}
return is_negative ? "-" + ans : ans;
}
};
【Java】
class Solution {
public String convertToBase7(int num) {
if (num == 0) {return "0";}
boolean is_negative = num < 0;
if (is_negative) {num = -num;}
String ans = "";
while (num > 0) {
int a = num / 7, b = num % 7;
ans = Integer.toString(b) + ans;
num = a;
}
return is_negative ? "-" + ans : ans;
}
}