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].
1 public class Solution { 2 public String convertToBase7(int num) { 3 if (num == 0) return "0"; 4 5 StringBuffer result = new StringBuffer(); 6 Boolean isNegative = false; 7 if (num < 0) { 8 isNegative = true; 9 num = -num; 10 } 11 12 while (num != 0) { 13 int insertMe = num % 7; 14 result.insert(0, Integer.toString(insertMe)); 15 num /= 7; 16 } 17 if (isNegative) result.insert(0, "-"); 18 return result.toString(); 19 } 20 }
1 public class Solution { 2 public String convertToBase7(int num) { 3 if (num == 0) return "0"; 4 5 Boolean isNegative = num < 0; 6 num = Math.abs(num); 7 8 String result = ""; 9 while (num != 0) { 10 result = Integer.toString(num % 7) + result; 11 num /= 7; 12 } 13 return isNegative ? "-" + result : result; 14 } 15 }