算法练习LeetCode初级算法之其他

  • 位1的个数

  • 解法一:

    class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        return Integer.bitCount(n);

    }

    }

  • 解法二:

    记住一点,前面的零没用的不要!!

    class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int k=0;

        while (n>0) {

                if (n%2==1) {

                    k++;

                }

                n/=2;

            }

        return k;

    }

    }

  • 汉明距离

    class Solution {

    public int hammingDistance(int x, int y) {

    int k=0;

    while (x>0||y>0) {

                if (x%2!=y%2) {

                    k++;

                }

                x/=2;

                y/=2;

            }

    return k;

    }

    }

原文地址:https://www.cnblogs.com/GavinYGM/p/10427516.html