您的位置:首页 > 其它

位处理:191. Number of 1 Bits&&190. Reverse Bits&&7. Reverse Integer

2017-02-26 12:46 141 查看
191

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3

class Solution {
public:
int hammingWeight(uint32_t n) {

int res=0;
while(n){
n&=n-1;//each loop we remove a 1 from n, 因为n和n-1只差一个1
++res;
}
return res;
}
};

190.
Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

class Solution {
public:
uint32_t reverseBits(uint32_t n) {

if(!n) return 0;
int res=0;

for(int i=0; i!=32; ++i){
res<<=1;
if(n&1) res++;
n>>=1;
}

return res;

}
};

这种题的共性是什么,一定要判断n是否为0.

7.

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

这题其实和reverse bits思路一致,都是先取出个位数,然后加到res上,res每轮*2或者*10,这样最后个位数就会变到最高位数上,而原先最高的位数随着原先数字每轮/2或者/10最后变成个位数。但是要注意x<0以及res超出int表示范围的情况。

class Solution {
public:
int reverse(int x) {

if(x==0) return 0;
int n=1;
if(x<0) {x*=-1; n=-1;}
long int res=0;
while(x){
res*=10;
res+=x%10;
x/=10;
}

if(res>INT_MAX||res<INT_MIN) return 0;
return res*n;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: