// Determine the binary form of A number: 1 # include <iostream> using namespace STD; int bxy (int I) {int COUNT = 0; while (I! = 0) {if (I % 2 = 1) {count ++;} // shift one I = I/2;} return count;} void main () {// 1100101int I = 101; cout <bxy (I) <Endl ;}
The following uses bitwise operations to improve efficiency!
# Include <iostream> using namespace STD; int bxy (int I) {int COUNT = 0; while (I! = 0) {if (I & 1 = 1) {count ++;} // shift one I = I> 1;} return count;} void main () {// 1100101int I = 101; cout <bxy (I) <Endl ;}
When I <0, the above method is finished and the endless loop is finished.
# Include <iostream> using namespace STD; int bxy (int I) {int COUNT = 0; // unsigned number, traversal: 1-> 2-> 4->... -> 2 ^ 32-> 0 unsigned int flag = 1; while (FLAG) {if (I & flag) {count ++;} flag = Flag <1 ;} return count;} void main () {// 32int I =-1; cout <bxy (I) <Endl ;}
# Include <iostream> using namespace STD; int bxy (int I) {int COUNT = 0; while (I) {++ count; I = (I-1) & I ;} return count;} void main () {cout <bxy (-1) <Endl ;}