0

How to calculate number of 1s in a binary number?

17th Oct 2016, 12:19 PM
Cheung Kim Fung
Cheung Kim Fung - avatar
9 odpowiedzi
+ 2
public class IntegerToBinary { public static void main(String[] args) { int x = 102; int cnt=0; String y = Integer.toBinaryString(x); System.out.println("Binary conversion is: " + y); for (int i=0; i<y.length();i++) { if (y.substring(i, i+1).equals("1")) { cnt =cnt+1; } } System.out.println("1's are: " + cnt); //one more way cnt=0; char[] z = y.toCharArray(); for (int i=0; i<z.length;i++) { if (Character.toString(z[i]).equals("0")) { cnt =cnt+1; } } System.out.println("0's are : "+cnt); } }
17th Oct 2016, 5:48 PM
Piyush Marda
Piyush Marda - avatar
+ 1
haha I mean in assembly language
17th Oct 2016, 12:23 PM
Cheung Kim Fung
Cheung Kim Fung - avatar
+ 1
how about in java. I just want to know how it works.
17th Oct 2016, 12:48 PM
Cheung Kim Fung
Cheung Kim Fung - avatar
+ 1
public class solution{ public static void main(String arcs[]){ string binnumber = Integer.toString(100,2); //converting 100 into binary int count = 0; for(int i=0; i<binnumber.length(); i++){ String c = Character.toString(text.charAt(i)) if(c.equals("1")) count++; } System.out .println(count); } }
19th Oct 2016, 10:12 AM
Akash Middinti
0
use a calculator
17th Oct 2016, 12:19 PM
qwertyuiop
0
1s ? Um....Can you tell me the thing you confused :)?(Becus some word you use I'm falling in confused too) If I can give advice I will
17th Oct 2016, 12:36 PM
Very hard!
Very hard! - avatar
0
I am a bit confused.. For example, x=5, print number of 1s =2
17th Oct 2016, 1:16 PM
Cheung Kim Fung
Cheung Kim Fung - avatar
0
Ok I think he help you for now
17th Oct 2016, 6:19 PM
Very hard!
Very hard! - avatar
0
yea he is
17th Oct 2016, 6:24 PM
Cheung Kim Fung
Cheung Kim Fung - avatar