How to calculate up 1s and 0s of a binary? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to calculate up 1s and 0s of a binary?

I am using bin() function to convert decimal to binary but i need to sum up 1s and 0 in binary

27th Jan 2021, 11:25 AM
Nodirbek Anorboy
Nodirbek Anorboy - avatar
3 Answers
+ 8
very similar to Ipangs suggestion, but i want to present it anyway: - use bin() function to convert integer to binary string - **as binary sign "0b" is preceeded to the resulting string, use a slice to do the following steps (<binary_string>[2:)] - use string method count() to get the number of "1" (<binary_string>[2:].count("1") - use string method count() to get the number of "0" (<binary_string>[2:].count("0")
27th Jan 2021, 2:02 PM
Lothar
Lothar - avatar
+ 7
- Crop binary number sign '0b' - Use len() to get total bits - Use <binary_string>.count() to count '1' - Subtract total bits by number of '1' bits to count '0'. https://code.sololearn.com/c60biWemCjB7/?ref=app
27th Jan 2021, 11:54 AM
Ipang
+ 7
This is a good exercise. Please link here your attempt first then anybody can help.
27th Jan 2021, 11:55 AM
JaScript
JaScript - avatar