二進制數中1的個數

二進制數中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 閱讀(...) 評論(...) 編輯 收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章