0
点赞
收藏
分享

微信扫一扫

【LeeCode】461. 汉明距离


【题目描述】

两个整数之间的 ​​汉明距离​​ 指的是这两个数字对应二进制位不同的位置的数目。

给你两个整数 ​​x​​​ 和 ​​y​​,计算并返回它们之间的汉明距离。

​​https://leetcode.cn/problems/hamming-distance/​​


【示例】

【LeeCode】461. 汉明距离_格式化输出


【代码】admin

这里要做二进制转换后,利用String.format格式化输出进行对比

package com.company;
class Solution {

public int hammingDistance(int x, int y) {
String str = Integer.toBinaryString(x);
String sss = Integer.toBinaryString(y);

// 格式化输出: 1 = 00000000000000000000000000000001
// 格式化输出: y = 00000000000000000000000000000100
str = String.format("%32s", str).replaceAll(" ", "0");
sss = String.format("%32s", sss).replaceAll(" ", "0");
int num = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != sss.charAt(i)){
num++;
}
}
System.out.println(num);
return num;
}
}

public class Test {
public static void main(String[] args) {
int x = 1;
int y = 4;

new Solution().hammingDistance(x, y);
}
}

【代码2】

异或: 相同则为0  不同则为1

package com.company;
class Solution {

public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}

public class Test {
public static void main(String[] args) {
int x = 1;
int y = 4;

new Solution().hammingDistance(x, y);
}
}

【运算符】

学习参考:​​https://blog.csdn.net/xiashaoqi/article/details/126405713​​

算数运算符

【LeeCode】461. 汉明距离_运算符_02


关系运算符

【LeeCode】461. 汉明距离_运算符_03


逻辑运算符


位运算

【LeeCode】461. 汉明距离_格式化输出_04

与运算

a & b 

相同位的两个数字都为1,则为1;若有一个不为1,则为0

或运算

a|b

相同位只要一个为1即为1

异或运算

a^b

相同位不同则为1,相同则为0

取反运算

~a

把0和1 全部取反

左移

a<<b

a向左移动一个



举报

相关推荐

0 条评论