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].
public class demo1 {
public String convertToBase7(int num) {
String result="";
if(num==0) result="0";
int number=Math.abs(num);
while (number>0) {
int b=number%7;
number=number/7;
result=String.valueOf(b)+result;
}
if(num<0) {
result="-"+result;
}
return result;
}
public static void main(String[] args){
int num=-7;
demo1 r = new demo1();
System.out.println(r.convertToBase7(num));
}
}
提交答案后,看到leetcode讨论区中的一个答案,只有五行,递归,简单到爆,特地copy过来膜拜膜拜。
public String convertToBase7(int num) {
if (num < 0)
return '-' + convertToBase7(-num);
if (num < 7)
return num + "";
return convertToBase7(num / 7) + num % 7;
}