+ 3
Can someone help me with Binary convertor
My 4th test case is not passing. Please someone let me know where my code is lacking import java.util.Scanner; public class Program { public static int toBinary(int n, int k) { return (n==0)? 0 :(( n % 2)*k) + toBinary (n/2,k*10); } public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int sum = toBinary(x, 1); System.out.println(sum); } }
1 Answer
+ 2
It's because you store binary representation in a variable of type "int". Your algorithm is doing fine until the "sum" reaches "int" limit (2,147,483,648 or in your case 1,111,111,111). I recommend using this one:
public static String toBinary(int n) {
String bin = "";
while (n > 0) {
bin = (n%2) + bin;
n /= 2;
}
return ;
}