Skip to content

Commit 8bd065f

Browse files
add: reverse bits
1 parent e792b7e commit 8bd065f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
class Solution {
3+
public int reverseBits(int n) {
4+
int result = 0;
5+
6+
for (int i = 0; i < 32; i++) {
7+
// result๋ณ€์ˆ˜ ๋น„ํŠธ ์™ผ์ชฝ ํ•œ์นธ ์‹œํ”„ํŠธ. LSB ๋Š” 0์œผ๋กœ ์ดˆ๊ธฐํ™”.
8+
result <<= 1;
9+
10+
// n ๋ณ€์ˆ˜์˜ ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ๋น„ํŠธ๋ฅผ(LSB) result ๋ณ€์ˆ˜์— ํ• ๋‹น.
11+
result = result | (n & 1);
12+
13+
// n ๋ณ€์ˆ˜ ์˜ค๋ฅธ์ชฝ ์‹œํ”„ํŠธ(๋„˜์–ด๊ฐ€๋Š” ๋น„ํŠธ๋Š” ๋ฌด์‹œ)
14+
n >>>= 1;
15+
}
16+
17+
return 0;
18+
}
19+
}
20+
21+
class AnotherSolution {
22+
public int reverseBits(int n) {
23+
// NOTE: ์ด์ง„ ๋ฐฐ์—ด๋กœ๋ณ€ํ™˜ (์Œ์ˆ˜์˜ ๊ฒฝ์šฐ 1๋กœ ๋น„ํŠธ๊ฐ€ ํ‘œํ˜„๋˜๊ธฐ ๋•Œ๋ฌธ์— ์–‘์ˆ˜ ๊ฒฝ์šฐ๋งŒ ์ฒ˜๋ฆฌ.)
24+
String binary = String.format("%32s", Integer.toBinaryString(n)).replace(" ", "0");
25+
String reverse = new StringBuilder(binary).reverse().toString();
26+
27+
// NOTE: int์ž๋ฃŒํ˜•์œผ๋กœ ์ด์ง„์ˆ˜ ํŒŒ์‹ฑ์„ ํ•  ๋•Œ ํ‘œํ˜„๋ฒ”์œ„ (+- 21์–ต) ๊ฐ€ ๋„˜์–ด์„œ๊ฒŒ ๋˜๋ฉด ์˜ค๋ฅ˜ ๋ฐœ์ƒ
28+
// java.lang.NumberFormatException: For input string:
29+
// "10111111111111111111111111111111" under radix 2
30+
// Long ์ž๋ฃŒํ˜•์œผ๋กœ ์•ˆ์ „ํ•˜๊ฒŒ ํŒŒ์‹ฑํ•ด์•ผํ•จ.
31+
return (int) Long.parseLong(reverse, 2);
32+
}
33+
34+
}

0 commit comments

Comments
ย (0)