当前位置:网站首页>Leetcode sword finger offer brush questions - day 21

Leetcode sword finger offer brush questions - day 21

2022-07-05 23:05:00 DEGv587

Leetcode The finger of the sword Offer How to brush questions :

Leetcode The finger of the sword Offer Brush problem - Learning plan directory _DEGv587 The blog of -CSDN Blog

The finger of the sword Offer 15. Binary 1 The number of  

solution : An operation

public class Solution {
    public int hammingWeight(int n) {
        int ret = 0;
        while (n != 0) {
            ret += n & 1;
            n >>>= 1;
        }

        return ret;
    }
}
public class Solution {
    public int hammingWeight(int n) {
        int ret = 0;
        while (n != 0) {
            ret++;
            n &= (n - 1);
        }

        return ret;
    }
}

The finger of the sword Offer 65. Do not add, subtract, multiply or divide

solution : An operation

Non carry and :a ^ b

Carry sum :(a & b) << 1

and : Carry sum + Non carry and = (a ^ b) + ((a & b) << 1)

loop , When carry is 0 Exit from time

class Solution {
    public int add(int a, int b) {
        while (b != 0) {
            int c = (a & b) << 1;// Carry sum 
            a ^= b;// Non carry and 
            b = c;// take c Assign a value to b, here b Is carry and 
        }

        return a;
    }
}

原网站

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