解題思路:32位有符號整數的表示範圍:-2147483648—2147483647。32位無符號整數的表示範圍:0—2147483647+2147483648。如果輸入的無符號數大於2147483647,則會顯示成負數,所以當輸入數字小於0時,只需加上2147483647+1,之後按照整數求1的個數,此時需要將1的個數加1.
Java代碼實現:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
if(n==0) return 0;
if(n<0) {
System.out.print(n);
n+=2147483647+1;
System.out.print(n);
count++;
}
while(n!=0){
int mod=n%2;
if(mod==1) count++;
n=n/2;
}
return count;
}
}
原題題目:https://leetcode.com/problems/number-of-1-bits/版權聲明:本文爲博主原創文章,未經博主允許不得轉載。