본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_12 - Reverse Bits

by HaningYa 2020. 7. 12.
728x90

 

Account Login - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 


문제

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Follow up:

If this function is called many times, how would you optimize it?


class Solution {
    func reverseBits(_ n: Int) -> Int {
        //2진수 문자열로 변환
        var nStr : String = String(n,radix:2)
        //Int 배열로 변환
        var arr = nStr.compactMap{String($0)}
        //배열 뒤집기
        arr.reverse()
        //32비트 채우기(뒤집힌 배열이니 append)
        var bitneed = 32 - nStr.count
        var emptyarr = Array(repeating: "0",count: bitneed)
        arr += emptyarr
        //String으로 바꿈
        var reversedString  = arr.joined(separator: "")
        return Int(reversedString,radix:2)!
    }
}

 

 

 

 

728x90

댓글