LintCode-二進制中有多少個1

題目:編程

計算在一個 32 位的整數的二進制表示中有多少個 1.spa

樣例

給定 32 (100000),返回 1code

給定 5 (101),返回 2blog

給定 1023 (111111111),返回 10it

 

編程:io

方式一:普通方法(思路就是進行斷除,注意先判斷餘數 L10 再覆蓋原來的整數 L13 的順序)class

 

 1 public class Solution {
 2     /**
 3      * @param num: an integer
 4      * @return: an integer, the number of ones in num
 5      */
 6     public int countOnes(int num) {
 7         // write your code here
 8         int count = 0 ;
 9         while(num!=0){
10             if(num%2==1){
11                 count++;
12             }
13             num = num/2;
14         }
15         return count ;
16     }
17 };

 

 

 

 

方式二:高效方法(位運算,且須要知道n&(n-1)的做用能夠消掉最右邊的1)原理

其原理是不斷清除n的二進制表示中最右邊的1,同時累加計數器,直至n爲0。
爲何n &= (n – 1)能清除最右邊的1呢?由於從二進制的角度講,n至關於在n - 1的最低位加上1。
舉個例子,8(1000)= 7(0111)+ 1(0001),因此8 & 7 = (1000)&(0111)= 0(0000),清除了8最右邊的1(其實就是最高位的1,由於8的二進制中只有一個1)。再好比7(0111)= 6(0110)+ 1(0001),因此7 & 6 = (0111)&(0110)= 6(0110),清除了7的二進制表示中最右邊的1(也就是最低位的1)
 1 public class Solution {
 2     /**
 3      * @param num: an integer
 4      * @return: an integer, the number of ones in num
 5      */
 6     public int countOnes(int num) {
 7         // write your code here
 8         int count = 0 ;
 9         while(num!=0){
10             num = num&(num-1);
11             count++;
12         }
13         return count ;
14     }
15 };
相關文章
相關標籤/搜索