算法练习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;

    }

    }

posted @ 2019-02-24 19:33  GavinYGM  阅读(94)  评论(0编辑  收藏  举报