用位运算将十进制转为二进制python_用位运算实现十进制转换为二进制

代码如下:

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 example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

算整数 n 的 Hamming weight,也就是其二进制位中非零位的个数。

AC代码:

1 inthammingWeight(uint32_t n) {2 int i, ans=0;3 for (i=31; i>=0; i--)4 {5 if (n & (1 << i)) ans++;6 }7 returnans;8 }

LeetCode 上的第二题:

Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:

If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

AC代码:

1 uint32_t reverseBits(uint32_t n) {2 inti;3 uint32_t ans;4

5 if (n & 1) ans=1;6 else ans=0;7 for (i=1; i<=31; i++)8 {9 ans <<= 1;10 if ((n & (1 << i))) ans |= 1;11 }12

13 returnans;14 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值