问题:
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].
解决:
① 获取数字的7进制表示。
class Solution {//19ms
public String convertToBase7(int num) {
if(num == 0) return "0";
StringBuilder sb = new StringBuilder();
boolean isNeg = false;
if(num < 0){
isNeg = true;
num = - num;
}
while(num != 0){
sb.append(num % 7);
num /= 7;
}
if(isNeg) sb.append("-");
return sb.reverse().toString();
}
}
② 直接转换为7进制数,最后再转换为字符串。
class Solution {//19ms
public String convertToBase7(int num) {
boolean isNegative = false;
if(num < 0) {
isNegative = true;
num = -num;
}
int result = 0;
int multiple = 1;
while(num > 0) {
int rem = num % 7;
num = num / 7;
result = (rem * multiple) + result;
multiple *= 10;
}
if(isNegative) {
result = -result;
}
return String.valueOf(result);
}
}