forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrivkode.java
More file actions
54 lines (39 loc) ยท 1.58 KB
/
rivkode.java
File metadata and controls
54 lines (39 loc) ยท 1.58 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
1. ๋ฌธ์ ์ดํด
์ ๋ฌ๋ฐ์ int ๋ฅผ binary bit ๋ก ๋ณํํ๋ค
๋ณํํ ๊ฐ์ reverse ๋ค์ง์ด์ ๋ค์ int๋ก ๋ณํํ๋ค
2. ์๊ณ ๋ฆฌ์ฆ
.toBinaryString() ๊ณผ .toUnsignedInt() ๋ฉ์๋๋ฅผ ํ์ฉํ๋ค
3. ์์ธ
n ๊ฐ์ sign ์ด๋ฏ๋ก ์ต๋ 21์ต๊น์ง ํํ์ด ๊ฐ๋ฅํ๋ค
n์ 0๋ณด๋ค ํฌ๋ฏ๋ก ํญ์ ์ฒซ๋ฒ์งธ bit๊ฐ์ 0์ด๋ค
4. ๊ตฌํ
์ ๋ฌ๋ฐ์ n์ bit๋ก ๋ณํ
๋ณํํ string์ stack ์ ์ฌ์ฉํด์ push peek ํ์ฌ reverse
๋ณํํ bit ๊ฐ์ ๋ค์ int๋ก ๋ณํ
์ฒ์์๋ stack์ ์ฌ์ฉํ๋ ค ํ์ผ๋ ์ต๋ bit ์๊ฐ ์ ํ์ ์ฝ 30๊ฐ ์ด๋ฏ๋ก
๋งค๋ฒ String์ ์์ฑํ๊ฑฐ๋ StringBuilder๋ฅผ ์ฌ์ฉํด๋ ๋ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ
๊ตณ์ด ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ง๋ค์ด์ ์ฌ์ฉํ ํ์๊ฐ ์์๊น ?
toBinaryString() ์ ํ๋ฉด 32์นธ์ ์ฑ์ฐ์ง ๋ชปํ ์ ์์ผ๋ฏ๋ก ๋ง์ง๋ง์ ์ด ๋น 0 ์ ๋ํ ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผ ํ๋ค
๊ทธ๋์ผ ๋ค์ง์์๋ ์ ์ ๊ฒฐ๊ณผ ๋์ด
*/
import java.util.*;
class Solution {
public int reverseBits(int n) {
String bit = Integer.toBinaryString(n);
StringBuilder sb = new StringBuilder();
for (int i=bit.length() - 1; i>=0; i--) {
System.out.println(i);
char c = bit.charAt(i);
int temp = c - '0';
sb.append(String.valueOf(temp));
}
int size = bit.length();
int leadingZero = 32 - size;
for (int i=0; i<leadingZero; i++)
sb.append("0");
System.out.println(sb.toString());
int decimalValue = Integer.parseInt(sb.toString(), 2);
return decimalValue;
}
}