Title Description
Given an integer, converted to binary 7, and outputs a string.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
NOTE: input range is [-1e7, 1e7].
Code
public class Solution {
public String convertToBase7(int num){
boolean isNegative = false;
int weight = 1;
StringBuilder sb = new StringBuilder();
String res;
//若为负数,转为正数处理
if(num<0){
isNegative = true;
num = -num;
}else if(num == 0){
return new String("0");
}
//确定数量级
while(true){
if(num>=weight && num<weight*7){
break;
}else{
weight *= 7;
}
}
//若为负数,先append一个负号
if(isNegative){
sb.append("-");
}
while(weight>=1){
if(num>=weight){
int curr = 0;
for(int i=1;i<7;i++){
if(num>=weight*i && num<weight*(i+1)){
curr = i;
num -= weight*i;
break;
}
}
sb.append(curr);
}else{
sb.append(0);
}
weight /= 7;
}
res = sb.toString();
return res;
}
}
Think
this question is not difficult, but judge for various boundary conditions should be fine, for example, is greater than or equal greater than, in the face of a number of test cases, wrong section of the opening and closing may cause can not pass.
Performance