当前位置:网站首页>Sword finger offer 15.65.56 I 56Ⅱ. Bit operation (simple - medium)

Sword finger offer 15.65.56 I 56Ⅱ. Bit operation (simple - medium)

2022-06-26 14:14:00 hedgehog:

Combined with another bit operation blog post :

An operation Practice with the questions _ Cat tapping code -CSDN Blog Basic knowledge of bit operation 136 、137、260 、645https://blog.csdn.net/weixin_52373240/article/details/121941063?spm=1001.2014.3001.5501

15.

subject :

The finger of the sword Offer 15. Binary 1 The number of icon-default.png?t=M1FBhttps://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/

 

  idea : Traverse every bit , Judge whether it is bit 1, Add up .

Code :

public class Solution {
    // you need to treat n as an unsigned value
    // n  An unsigned number 
    public int hammingWeight(int n) {
        int cnt=0;
        for(int i=0;i<32;i++){
            // This one is 1
            if(((n>>i)&1)==1)
                cnt++;
        }
        return cnt;
    }
}

result :

65.

subject :

The finger of the sword Offer 65. Do not add, subtract, multiply or divide icon-default.png?t=M1FBhttps://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/

  idea : Traverse each bit of the two addends , Record this bit 1 The number of , And add carry . Yes 1 Number judgment of , And respond to the operation ( See the code ).

Code :

class Solution {
    public int add(int a, int b) {
        int addOne=0;// carry 
        int res=0;// result 

        for(int i=0;i<32;i++){
            int cntOne=0;
            // If a This bit is 1
            if(((a>>i)&1)==1)
                cntOne++;
            // If b This bit is 1
            if(((b>>i)&1)==1)
                cntOne++;

            // Plus carry 
            cntOne+=addOne;
            if(cntOne==2){ //  This bit has two 1
                //  Make this bit 0, Carry is 1
                // res|=(0<<i);
                addOne=1;
            }
            else if(cntOne==3){ //  This bit has two 1 And a carry 
                //  Make this bit 1, Carry is 1
                res|=(1<<i);
                addOne=1;
            }else{ //if(cntOne<=1)  This bit has a 1 Or not 1( Two 0)
                //  Make this bit 0 or 1( namely cntOne Value ), No carry 
                res|=(cntOne<<i);
                addOne=0;
            }
        }
        return res;
    }
}

result :

 

56Ⅰ.56Ⅱ.

See another post :

An operation Practice with the questions _ Cat tapping code -CSDN Blog Basic knowledge of bit operation 136 、137、260 、645https://blog.csdn.net/weixin_52373240/article/details/121941063?spm=1001.2014.3001.5501

原网站

版权声明
本文为[hedgehog:]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170509326892.html