代码如下:
1 #include //将十进制数转化为二进制数,位运算的取位操作
2 using namespacestd;3 intmain()4 {5 unsigned shorti;6 cout << "请输入一个小于65536的正整数" <>i;8 for(int j=15; j >= 0; j--)9 {10 if ( i & ( 1 << j) ) cout << "1";11 else cout << "0";12 }13 cout <
14
15 return 0;16 }
分析:
分析一下这个程序的算法原理,顺便复习一下位运算的奇妙吧。
这是一个将无符号十进制数转化为标准16位二进制数的程序。
程序的主体部分,for语句从15递减到0,一共16次对二进制数的每一位的判断作操作。循环体内部的条件判断用到了位运算中的&运算(与运算)和<
所以i&(1<
有的童鞋可能觉得用mod(取余)运算照样可以达到效果,但是位运算的“个性”就决定了它直接对数据的二进制形式进行操作的快捷性(一般计算机的数据存储基本形式为二进制形式),两个相同算法的程序,用了位运算后会使程序速度上有提高。
类似的 LeetCode 上的第一题 :
Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For exampl