三種方式求: 輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼表示


package com.example;

public class Solution {
/*
* 轉化成2進制數計算
*/
public int NumberOf1(int n) {
String string = Integer.toBinaryString(n);
int count = 0;
for (int i = 0;i < string.length();i++) {
if (string.charAt(i) == '1') {
count++;
}
}
return count;
}
/*
* 使用邏輯與運算方法
*/
public int NumberOf2(int n) {
int count = 0;
for (int i = 0; i < Integer.SIZE;i++) {
if ((n & 1) == 1) {
count++;
}
n = n >> 1;
}
return count;
}
/*
* 使用除法進行運算
*/
public int NumberOf3(int n) {
//這里負數因為要用第33位,所以要使用long類型
long L = 1L;
if (n < 0) {
L = (L << 32) + n;
} else {
L = n;
}
int count = 0;
long temp = 0;
while (true) {
temp = 0;
temp = L % 2;
/*
* 遇到余數為1的情況就加一
*/
if (temp == 1) {
count++;
L--;
}
L /= 2;
if (L == 0) {
break;
}
}
return count;
}
public static void main(String [] args) {
Solution solution = new Solution();
int []temp = new int[3];
temp[0] = solution.NumberOf2(-3);
temp[1] = solution.NumberOf2(-3);
temp[2] = solution.NumberOf2(-3);
for (int i =0;i<3;i++) {
System.out.println(temp[i]);
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM