File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed
src/com/andavid/leetcode/_461 Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -24,7 +24,7 @@ Explanation:
2424The above arrows point to positions where the corresponding bits are different.
2525```
2626
27- ## 思路
27+ ## 思路一
2828
2929求两个整数的二进制表示中,不同的 bit 位数量。异或操作符,相同位运算后为 0,不同位运算后为 1,因此只需要求两个整数经过异或之后,对应的二进制表示中 1 的数量。
3030
@@ -47,5 +47,20 @@ class Solution {
4747}
4848```
4949
50+ ## 思路二
51+
52+ 使用 Integer.bitCount 获取二进制数 bit 位中 1 的数量。
53+
54+ ## [ 完整代码] [ src2 ]
55+
56+ ``` java
57+ class Solution {
58+ public int hammingDistance (int x , int y ) {
59+ return Integer . bitCount(x^ y);
60+ }
61+ }
62+ ```
63+
5064[ title ] : https://leetcode.com/problems/hamming-distance
5165[ src ] : https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_461/Solution.java
66+ [ src2 ] : https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_461/Solution2.java
Original file line number Diff line number Diff line change 1+ class Solution2 {
2+ public int hammingDistance (int x , int y ) {
3+ return Integer .bitCount (x ^y );
4+ }
5+
6+ public static void main (String [] args ) {
7+ Solution solution = new Solution ();
8+ System .out .println (solution .hammingDistance (1 , 4 ));
9+ }
10+ }
You can’t perform that action at this time.
0 commit comments