zoukankan      html  css  js  c++  java
  • Hamming Distance

    1. Title

    461. Hamming Distance

    2. Http address

    https://leetcode.com/problems/hamming-distance/?tab=Description

    3. The question

    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.

    4. Code
    public class Solution {
        public int hammingDistance(int x, int y) {
            
            String xbits = Integer.toBinaryString(x);
            String ybits = Integer.toBinaryString(y);
    
            int lenX = xbits.length();
            int lenY = ybits.length();
            int re = 0, i = 0, j = 0;
            if (lenX > lenY) {
                for (i = 0; i < lenX - lenY; i++) {
                    if (xbits.charAt(i) != '0') {
                        re++;
                    }
                }
    
            } else {
                for (j = 0; j < lenY - lenX; j++) {
                    if (ybits.charAt(j) != '0') {
                        re++;
                    }
                }
            }
    
            while (i < lenX && j < lenY) {
                if (xbits.charAt(i++) != ybits.charAt(j++)) {
                    re++;
                }
            }
    
            return re;
        
        }
    }



  • 相关阅读:
    总结:关于作用域的经典面试题
    解决JS拖拽出现的问题
    JS正则(3)总结
    JS正则(2)对正则的理解
    JS 闭包 正则(1)
    JS Date对象
    笔记
    9.13笔记
    9.12学习笔记
    9.11学习笔记
  • 原文地址:https://www.cnblogs.com/ordili/p/6515658.html
Copyright © 2011-2022 走看看