位运算习题

位运算的题

1 231. 2的幂次方

class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n==0)return false;
        while((n&1)==0){n>>=1;}
        if(n==1)return true;
        else return false;}}

只要是最高位是1 其他位是0 的就true

2 191. 位为1的个数

1111 0111 输出 7

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        if (n==0) return 0;
        int res = 0;
        while(n!=0){
        res+=(n&1);
        n>>>=1;
        }
        return res;
    }
}

逻辑右移,避免负数的符号位不动。

终止条件为 n==0

3 只出现一次的数字

按位亦或,两个相同的亦或结果为0

class Solution {
    public int singleNumber(int[] nums) {
        int ans=0;
        for(int i = 0;i<nums.length;i++){
                ans^=nums[i];
        }
        return ans;
    }
}
posted @ 2021-12-10 16:01  淮南枳  阅读(43)  评论(0)    收藏  举报