File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You canโt perform that action at this time.
0 commit comments