+ 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); } }

11th Jan 2021, 5:57 PM
Lukesh Singla
Lukesh Singla - avatar
1 Respuesta
+ 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 ; }
11th Jan 2021, 7:49 PM
Mohammad Reza Sharifi Khorasani
Mohammad Reza Sharifi Khorasani - avatar