Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- Math
- greedy
- Stack
- Method
- 코테
- string
- 구현
- hash table
- Counting
- geometry
- array
- Binary Tree
- database
- implement
- Number Theory
- SQL
- java
- simulation
- 자바
- 파이썬
- Data Structure
- Tree
- dynamic programming
- Class
- Binary Search
- bit manipulation
- Matrix
- sorting
- 코딩테스트
- two pointers
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 461. Hamming Distance 본문
1. Input
1) 정수 x
2) 정수 y
2. Output
1) x, y의 hamming distance
2) hamming distance란 두 정수를 2진수로 나타냈을 때 같은 위치, 다른 bit의 수
3. Constraint
1) 0 <= x, y <= 2^31 - 1
4. Example
Input: x=1, y=4 -> Output: 2
설명: 1과 4를 2진수로 나타내면
1 = 0 0 0 1
4 = 0 1 0 0 이고, 앞에서 2번째, 4번째 bit가 서로 다르므로 2를 반환한다.
5. Code
1) 첫 코드(2022/06/16)
int count = 0;
String s1 = Integer.toBinaryString(x);
String s2 = Integer.toBinaryString(y);
String p = "";
if(x > y){
for(int i=0 ; i<s1.length()-s2.length() ; i++)
p += "0";
s2 = p + s2;
}
else{
for(int i=0 ; i<s2.length()-s1.length() ; i++)
p += "0";
s1 = p + s1;
}
for(int i=0 ; i<s1.length() ; i++)
if(s1.charAt(i) != s2.charAt(i))
count++;
return count;
2) 다시 풀어본 코드(2022/11/30)
int answer = 0;
while(x>0 || y>0){
if(x%2 != y%2) answer++;
x /= 2; y /= 2;
}
return answer;
- 공간절약도, 속도도 모두 2번이 낫다.
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 500. Keyboard Row (0) | 2022.11.30 |
---|---|
[LeetCode/Easy] 476. Number Complement (0) | 2022.11.30 |
[LeetCode/Easy] 434. Number of Segments in a String (0) | 2022.11.30 |
[프로그래머스/Lv.1] 삼총사 (0) | 2022.11.30 |
[LeetCode/Easy] 412. Fizz Buzz (0) | 2022.11.29 |