题目:编程
计算在一个 32 位的整数的二进制表示中有多少个 1
.spa
给定 32
(100000),返回 1
code
给定 5
(101),返回 2
blog
给定 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)原理
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 };