Leetcode 461(Java)
来源:互联网 发布:win7局域网网络图标 编辑:程序博客网 时间:2024/06/13 14:10
今天长春的天气很好阿,解题思路都跟着比较清晰嘻嘻。先贴上题目:The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
要比较每一位的差别脑子里第一个蹦出来的就是按位来做运算,用0来按位或不好实现左右移,那么就用一个1来按位与。开辟一个新变量,首先将1放在最低位,与输入的x,y按位与,比较结果即可知道x,y的最低位是否相同,接下来把这个1往左移动,就可以继续比较x,y的更高位数啦,AC代码如下: public class Solution {
public int hammingDistance(int x, int y) {
int num = 0;
for(int i=0;i<32;i++){
int compare=1<<i;
if((compare&x)!=(compare&y)){
num++;
}
}
return num;
}
}
- Leetcode 461(Java)
- Leetcode(java)
- leetcode java
- [LeetCode]Next Permutation java leetcode
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] ZigZag Conversion (Java)
- [Leetcode] Reverse Integer (Java)
- [Leetcode] Palindrome Number (Java)
- [Leetcode] Valid Parentheses (Java)
- [Leetcode] Generate Parentheses (Java)
- [Leetcode] Remove Element (Java)
- [Leetcode] Implement strStr() (Java)
- [Leetcode] Next Permutation (Java)
- [Leetcode] Valid Sudoku (Java)
- [Leetcode] Sudoku Solver (Java)
- [Leetcode] Combination Sum (Java)
- [Leetcode] Multiply Strings (Java)
- 01 PHP 简介
- SVN中Commit出现乱码的解决方案
- [数据结构]--jdk1.8中HashMap源码解析
- JUC - Condition 源码分析
- 一个完整的Mybatis分页解决方案
- Leetcode 461(Java)
- 【记录】搭建ANTLR v4开发环境
- 02 PHP 语法
- Py第八问 Pycharm连接Github
- cookie机制及cookie的应用
- 03 PHP 变量和常量
- js基础:数组基础和数组方法的各种使用
- 03上机练习1网易邮箱
- 简易拖拽以及bug的修复