+ 1

In the "toInteger()" methode , why the output of k is always a random number ??? I don't understand

import java.util.Scanner; //your code goes here public class Converter { //Methode to convert a number to binary numbre public static int toBinary(int x){ String binary=""; while(x > 0) { binary = (x%2)+binary; x /= 2; } return toInteger(binary) ; } //to convert String to Integer public static int toInteger (String ch){ int k =0 ; int a=1; //System.out.println(ch.length()); for(int i=0 ; i<ch.length() ; i++){ k = k*a ; k += ch.charAt(i) ; a*=10; } return k ; } } public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Converter.toBinary(x)); } }

16th Mar 2021, 5:25 PM
Mugiwara boy
Mugiwara boy - avatar
4 Respostas
+ 2
I think you need to modify a line inside your toInteger() method. k += Integer.valueOf((String.valueOf(ch.charAt(i)))) ; Because character are treated as integers internally so when you use ch.charAt(i) then it will take it's ASCII value and add to the value of 'k'. Just an example int a = 7 + '1'; // Output a = 56
16th Mar 2021, 5:56 PM
Avinesh
Avinesh - avatar
+ 1
As already mentioned above, ch.charAt(i); is returns a ASCII value there.. So convert to int digit by subtracting 48 and just do like this for(int i=0 ;i<ch.length(); i++){ k = k*10 ; k +=(ch.charAt(i)- 48); //a*=10; }
16th Mar 2021, 6:57 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 thank you , it worked
16th Mar 2021, 7:36 PM
Mugiwara boy
Mugiwara boy - avatar
0
Avinesh you are right , ch.charAt return the code ASCII but when i wrote Integer.valueOf .... the output was "Cannot find Symbol" What that's mean ?
16th Mar 2021, 7:35 PM
Mugiwara boy
Mugiwara boy - avatar