[코테 풀이] Hamming Distance

시내·2024년 6월 29일

Q_461) Hamming Distance

출처 : https://leetcode.com/problems/hamming-distance/

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

class Solution {
    public int hammingDistance(int x, int y) {
        int count = 0;
        String xBin = toBin(x);
        String yBin = toBin(y);
        if (xBin.length() > yBin.length()) {
            yBin = controlLen(xBin, yBin);
        } else if (xBin.length() < yBin.length()) {
            xBin = controlLen(yBin, xBin);
        }
        for (int j = 0; j < xBin.length(); j++) {
            if (xBin.charAt(j) != yBin.charAt(j)) {
                count++;
            }
        }
        return count;
    }

    public  String toBin(int x) {
        String bin = "";
        while (x > 0) {
            bin = (x % 2) + bin;
            x /= 2;
        }
        return bin;
    }

    public  String controlLen(String longer, String shorter) {
        String zeros = "";
        String after = "";
        for (int i = 0; i < longer.length() - shorter.length(); i++) {
            zeros += "0";
        }
        after = zeros + shorter;
        return after;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글