問題描述:java
輸入一個整數n,求n的二進制表示中,一共有多少個1。例如n=8,二進制表示爲00001000,二進制表示中有1個1。spa
分析:code
若是一個數n不爲0,那麼n-1的二進制表示,與n的二進制表示相比,n的二進制表示最右邊的1變爲0,而最右邊的1所對應的0所有變爲1。其他位不受影響。orm
例如:n的二進制表示爲****1000,則n-1的二進制表示爲****0111,則n&(n-1)的二進制表示爲****0000。將n二進制表示中最右邊的1去掉了。get
將n賦值爲n&(n-1),繼續循環此操做,直到n爲0。it
代碼實現:
io
package oschina.cc150; /** * @project: oschina * @filename: IT28.java * @version: 0.10 * @author: JM Han * @date: 3:20 PM 1/8/2016 * @comment: calculate the number of 1 in binary format * @result: Your test result */ public class IT28 { public static int getOneNum(int x){ int r = 0; while(x != 0){ x = x&(x-1); r++; } return r; } public static void main(String[] args) { int n = 20; System.out.println("The 1 in number: " + n + " is: " + getOneNum(n)); } }