Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

思路:二进制中1的个数 #8

Open
YZcxy opened this issue Apr 4, 2019 · 0 comments
Open

思路:二进制中1的个数 #8

YZcxy opened this issue Apr 4, 2019 · 0 comments

Comments

@YZcxy
Copy link
Owner

YZcxy commented Apr 4, 2019

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

思路

如果我们把这个数和1进行与运算,如果结果为1就说明最右边的数为1,然后把这个数右移一位,再次重复,知道这个数变为0,就可以统计一共有多少个1。
但是这种算法有问题就是遇到负数的时候,负数右移符号位是不会移动的,所以最后会陷入死循环。解决方案就是让这个数和1进行与运算,然后把1向左位移,这样就不会死循环。

可是这样循环效率还是不够高,如果有32位就需要循环32次。更优秀的算法是,把这个数减去1,然后与这个数进行与运算,这时候位于最右边的一个1就变成了0,所以这个数能进行多少次这个操作最后变成了0,这个数就有多少个1。
例如:
1100 减去 1 变成了 1011,1100 与 1011 就变成了 1000;
1000 减去 1 变成了 0111,1000 与 0111 就变成了 0000。
操作进行了两次,一共有两个1。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant