LeetCode 461. Hamming Distance

[原题链接](https://leetcode.com/problems/hamming-distance/description/)     
复制代码

我的源代码

    class Solution
    {
        public static int hammingDistance(int x, int y)
        {
            int hammingDistance = 0;
            Stack<Integer> xToBinary = transfer(x);
            Stack<Integer> yToBinary = transfer(y);
            int maxNumber = max(x,y);
            while(xToBinary.size() != 0)
            {
                if (maxNumber == x && xToBinary.size() > yToBinary.size())
                {
                    if (xToBinary.pop() == 1) hammingDistance++;
                }
                else if (maxNumber == y && yToBinary.size() > xToBinary.size())
                {
                    if (yToBinary.pop() == 1) hammingDistance++;
                }
                else if (xToBinary.pop() != yToBinary.pop()) hammingDistance++;
            }
            return hammingDistance;
        }
        public static Stack<Integer> transfer(int integer)
        {   
            Stack<Integer> binary  = new Stack<Integer>();
            if(integer == 0) binary.push(0);
            while(integer != 0)
            {
                binary.push(integer%2);
                integer /= 2;
            }
            return binary;
        }
        public static int max(int x,int y)
        {
            if(x > y) return x;
            else return y;
        }
 }
复制代码
  • 思路
    使用stack()

LeetCode优秀题解

^→ 异或
1.十进制数去异或:十进制数转为二进制数→对应取异或得到一个二进制数→转化为十进制数
2.bitCount
如图知,返回传入参数(2's补码)有1的数目(1代表异或为真,即汉明码+1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值