Love丶FFC's Blog

LintCode_easy:Hamming距离

2019-09-02 09:25:17
阅读:6830   •   评论:134
标签:,

描述

两个整数的Hamming距离是对应比特位不同的个数。
给定两个整数x和y,计算两者的Hamming距离。

0 ≤ xy < 231

样例

样例1

输入: x = 1 和 y = 4
输出: 2
解释:
1的二进制表示是001
4的二进制表示是100
共有2位不同

样例2

输入: x = 5 和 y = 2
输出: 3
解释:
5的二进制表示是101
2的二进制表示是010
共有3位不同

编程语言:Java

解题思想:

1.因为二进制数在Java中会自动消去前面的0,因此需要先将两个二进制数的长度补齐。例如1(10)=001(2),但在Java中会消去两个0,因而只显示1。

2.判断两个字符串的长度,例如A为0001,B为1000,则A需要补三个0才能对齐长度。补齐的长度根据两个字符串默认长度之差的绝对值。

3.补足0之后再将默认的二进制值紧随其后。

4.逐一比较各位是否相同。

时间复杂度:O(n)

IDE代码如下:

  1. package LintCode_Easy;
  2.  
  3. public class _835{
  4.  
  5. public static void main(String[] args) {
  6. int x = 5,y = 2;
  7. String xs="",ys="";
  8. int total = 0;
  9. for(int i=0;i<Math.abs((Integer.toBinaryString(x)).length()-(Integer.toBinaryString(y)).length());i++)
  10. {
  11. if((Integer.toBinaryString(x)).length()>(Integer.toBinaryString(y)).length())
  12. {
  13. ys+="0";
  14. }
  15. else
  16. {
  17. xs+="0";
  18. }
  19. }
  20. xs+=Integer.toBinaryString(x);
  21. ys+=Integer.toBinaryString(y);
  22. for(int i=0;i<xs.length();i++)
  23. {
  24. if(xs.charAt(i)!=ys.charAt(i))
  25. total++;
  26. }
  27. System.out.println(total);
  28. }
  29.  
  30. }
  31.  

LintCode编辑器代码如下:

  1. public class Solution {
  2. public int hammingDistance(int x, int y) {
  3. String xs="",ys="";
  4. int total = 0;
  5. for(int i=0;i<Math.abs((Integer.toBinaryString(x)).length()-(Integer.toBinaryString(y)).length());i++)
  6. {
  7. if((Integer.toBinaryString(x)).length()>(Integer.toBinaryString(y)).length())
  8. {
  9. ys+="0";
  10. }
  11. else
  12. {
  13. xs+="0";
  14. }
  15. }
  16. xs+=Integer.toBinaryString(x);
  17. ys+=Integer.toBinaryString(y);
  18. for(int i=0;i<xs.length();i++)
  19. {
  20. if(xs.charAt(i)!=ys.charAt(i))
  21. total++;
  22. }
  23. return total;
  24. }
  25. }

评论板

共有 134 条评论

  1. Abupguele

    Your interventional radiologist will place the biopsy needle into your skin and check its position with an MRI, CT, ultrasound, or fluoroscopy cialis generic cost The nurse should provide the client with which instruction

  2. invoimi

    Breast Feeding Reduces Maternal Lower Body Fat, Journal of the American Dietetic Association 93, no closest thing to levitra

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:510608