From 5747260d7de8fa2a7f6915e21465e4a5775ec772 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sat, 28 Dec 2024 02:38:32 +0900 Subject: [PATCH] reverse bits solved --- reverse-bits/mintheon.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 reverse-bits/mintheon.java diff --git a/reverse-bits/mintheon.java b/reverse-bits/mintheon.java new file mode 100644 index 000000000..f1c2ffcb7 --- /dev/null +++ b/reverse-bits/mintheon.java @@ -0,0 +1,24 @@ +public class Solution { + /** + 시간복잡도: O(1) -> 루프는 항상 32번 반복되기 때문 + 공간복잡도: O(1) + */ + + // you need treat n as an unsigned value + public int reverseBits(int n) { + int answer = 0; + int index = 31; + + while(n != 0) { + // n&1 : 마지막 비트를 추출 + // << : 0을 패딩처리 시켜서 상위 자리수로 올려버림 + answer += (n & 1) << index; + + // >>> : 부호 상관없이 오른쪽으로 비트 이동 + n = n >>> 1; + index--; + } + + return answer; + } +}