首页 > 代码库 > 461.求两个数字转成二进制后的“汉明距离” Hamming Distance

461.求两个数字转成二进制后的“汉明距离” Hamming Distance


  1. public class Solution {
  2. public int HammingDistance(int x, int y) {
  3. int distance = 0;
  4. string sX = Convert.ToString(x, 2);
  5. string sY = Convert.ToString(y, 2);
  6. int maxLength = Math.Max(sX.Length, sY.Length);
  7. //填充0,使两个字符串右对齐
  8. sX = sX.PadLeft(maxLength, ‘0‘);
  9. sY = sY.PadLeft(maxLength, ‘0‘);
  10. for (int i = 0; i < maxLength; i++) {
  11. if (sX[i] != sY[i]) {
  12. distance++;
  13. }
  14. }
  15. return distance;
  16. }
  17. }



来自为知笔记(Wiz)


461.求两个数字转成二进制后的“汉明距离” Hamming Distance