leetcode 461. 汉明距离(Java版)
題目
https://leetcode-cn.com/problems/hamming-distance/
題解
使用 Java 中的按位異或 ^ 運(yùn)算符:https://www.baeldung.com/java-xor-operator
For example, let’s consider two integers 1 and 3, whose binary representations are 00000001 and 000000011, respectively. Then, using the XOR operator between them will result in the integer 2.
Only the second bit is different in those two numbers, therefore the result of the XOR operator on this bit will be 1. All other bits are identical, thus their bitwise XOR result is 0, giving us a final value of 00000010 — the binary representation of the integer 2.
代碼
一行搞定:return Integer.bitCount(x ^ y);
public class Solution {public static int hammingDistance(int x, int y) {System.out.println(Integer.toBinaryString(x)); // 001System.out.println(Integer.toBinaryString(y)); // 100System.out.println(Integer.toBinaryString(x ^ y)); // 101return Integer.bitCount(x ^ y);}// for testpublic static void main(String[] args) {System.out.println(hammingDistance(1, 4));} }總結(jié)
以上是生活随笔為你收集整理的leetcode 461. 汉明距离(Java版)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 459. 重复的子字符
- 下一篇: leetcode 463. 岛屿的周长(