題目連接:https://leetcode.com/problems/number-of-1-bits/description/html
題目大意:與338題相似,求解某個無符號32位整數的二進制表示的1的個數。注意要求是無符號32位整數。算法
注意:無符號整數的範圍是0~2^32-1,而普通int的範圍是-2^31 ~ 2^31-1。編程
法一:直接用普通十進制轉二進制的辦法作,發現超時了,超時數據是2^31,當我把這個數放進eclipse中發現直接報錯,至於爲何在leetcode裏還能夠編譯經過,我也不知道。想看它的測試代碼,發現並無公開。代碼以下:eclipse
1 public int hammingWeight(int n) { 2 int cnt = 0; 3 while(n != 0) { 4 cnt += n & 1; 5 n >>= 1; 6 } 7 return cnt; 8 }
生氣!這段代碼用C++提交,AC了!耗時3ms,生氣!😠ide
法二(借鑑):用Integer自帶的轉爲無符號二進制的類庫作,ac了,矇蔽。代碼以下(耗時3ms):測試
1 public int hammingWeight(int n) { 2 int cnt = 0; 3 String s = Integer.toBinaryString(n);//轉爲無符號二進制 4 char[] binaries = s.toCharArray(); 5 for(char c : binaries) { 6 if(c == '1') { 7 cnt++; 8 } 9 } 10 return cnt; 11 }
法三(借鑑):編程之美P121解法3,只計數1的個數,將複雜度降爲只與1的個數有關。位運算很巧妙。代碼以下(耗時2ms):spa
1 public int hammingWeight(int n) { 2 int cnt = 0; 3 while(n != 0) { 4 //1001 5 //1001-1=1000 1001&1000=1000 6 //1000-1=0111 1000&0111=0 7 //1的個數是2,因此會計算兩次 8 n &= (n - 1); 9 cnt++; 10 } 11 return cnt; 12 }
法四(借鑑):只用循環32次,也就是用位運算n&(1<<i),取出數值n的每一位二進制的值,查看是否非0。代碼以下(耗時2ms):3d
1 public int hammingWeight(int n) { 2 int cnt = 0; 3 for(int i = 0; i <= 31; i++) { 4 //1<<i表示1左移i位,n&(1<<i)表示取n的第i位數值 5 if((n & (1<<i)) != 0) { 6 cnt++; 7 } 8 } 9 return cnt; 10 }
還有一些打表的算法,在這個博客裏面:http://www.cnblogs.com/stoneJin/archive/2011/10/26/2224900.htmlcode