public static void main(String[] args) { System.out.println(solution(10)); System.out.println(solution(27)); System.out.println(solution(12345)); // error here}public static int solution(int num) { Stack<Integer> stack = new Stack<>(); while (num > 0) { int r = num % 2; stack.push(r); num /= 2; } String res = ""; while (!stack.isEmpty()) { res += stack.pop(); } return Integer.parseInt(res);}
critique
I should use a StringBuilder instead of String because adding something to String
When concatenating to String using + it creates a new object each time → so use StringBuilder
A problem:
if i input 12345, java throws a Exception in thread "main" java.lang.NumberFormatException: For input string: "11000000111001"
The string generated ("11000000111001") represents a number that’s too large to fit into Java int
it’s about 11 trillion!
A maximum value a 32-bit int can hold is ~2 billion
the standard approach is to return a String
solution
public static void main(String[] args) { System.out.println(solution(10)); System.out.println(solution(27)); System.out.println(solution(12345)); } public static String solution(int num) { Stack<Integer> stack = new Stack<>(); while (num > 0) { int r = num % 2; stack.push(r); num /= 2; } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.toString(); }