Java實現求一個整數的二進位制數中1的個數
阿新 • • 發佈:2018-12-30
這題還是筆試的時候遇到的,當時沒有想太多,直接用了最為直接的移位相加的方法,雖然可以得出結果,但是程式效率低。
後來發現使用n=n&(n-1)的方法,效率會更高,先上程式碼。
<span style="font-size:18px;">public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int count = 0; while(n!= 0) { count++; n=n&(n-1); } System.out.println(count); } </span>
分析:while迴圈中只需要執行n中1的個數+1次。以n=19為例,二進位制數為:0001 0011
第一次迴圈:0001 0011 & 0001 0010 = 0001 0010
第二次迴圈:0001 0010 & 0001 0001 = 0001 0001
第三次迴圈:0001 0001 & 0001 0000 = 0001 0000
第四次迴圈:0001 0000 & 0000 1111 = 0000 0000 ,此時n=0,跳出迴圈。