二进制数中1的个数

题目:请设计一个函数,要求输入一个整数,然后输出此整数的二进制形式中1的个数,譬如:输入9(1001),输出2。

本题考察二进制数的操作,共有五种操作,都是把十进制数转化为二进制数之后再进行的按位操作

1、&操作:0&1=0、0&0=0、1&1=1、1&0=0;5&7=5

2、|操作:0|1=1、0|0=0、1|1=1、1|0=1;5|7=7

3、^操作:相异为1,相同为0;5^7=2

4、<<左移操作:m<<2,表示把m的二进制形式数,向左移动两位,后边补0(相当于乘以2)(一般情况)

5、>>右移操作:m>>2,表示把m的二进形式数,向右移动两位,若m最高位为1(负数),则在左边补1,若m最高位为0(正数),则在最左边补0

***有一个自己学过但居然忘了的东西要说一下(计组还得好好看啊)

-1在计算机中二进制形式到底是几?11111111 or 10000001

我居然第一次想都没想是10000001,但。。。计算机中是拿补码表示的(0.0),原码表示-1是10000001是对哒,但计算机会对10000001(负数),符号位不变,其他各位按位取反,得到反码11111110,然后再加1得到11111111,故-1中的1的个数在int型下是32个,而10000001表示的是-127。所以对于一个二进制数到底是几的问题?要看它是拿什么码表示的,然后再计算是几。。。

上题有三种的解法,一个比一个进行了优化和完善。

一、上图好了。。。

 

二、

三、

具体的代码实现和测试用例

 1 #include<iostream>
 2 using namespace std;
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5 int firstfind1(int n)
 6 {
 7     int c = 0;
 8     while (n)
 9     {
10         if (n & 1)
11             ++c;
12         n = n >> 1;
13     }
14     return c;
15 }
16 int secondfind1(int n)
17 {
18     int c = 0;
19     int flag = 1;
20     while (flag)
21     {
22         if (n&flag)
23             ++c;
24         flag = flag << 1;
25     }
26     return c;
27 }
28 int thirdfind1(int n)
29 {
30     int c = 0;
31     while (n)
32     {
33         ++c;
34         n = n&(n - 1);
35     }
36     return c;
37 }
38 int main()
39 {
40     //cout << firstfind1(-1) << endl;//死循环
41     /*
42     cout << firstfind1(13) << endl;
43     cout << secondfind1(13) << endl;
44     cout << secondfind1(1) << endl;
45     cout << secondfind1(0x70000000) << endl;
46     cout << secondfind1(0x80000000)<<endl;
47     cout << secondfind1(0x7FFFFFFF) << endl;
48     cout << secondfind1(0xFFFFFFFF) << endl;
49     cout << secondfind1(0x8FFFFFFF) << endl;
50     */
51     cout << secondfind1(-1) << endl;
52     cout << thirdfind1(-1) << endl;
53     cout << (5^7) << endl;//2
54     cout << (5 | 7) << endl;//7
55     cout << (5 & 7) << endl;//5
56     system("pause");
57     return 0;
58 }

总结:

 

posted @ 2016-04-21 16:33  General_up  阅读(477)  评论(0编辑  收藏  举报