728x90
문제
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
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode - Container With Most Water (0) | 2020.07.14 |
---|---|
💯 Daily LeetCode Challenge Day_13 - Same Tree (0) | 2020.07.13 |
💯 Daily LeetCode Challenge Day_11 - Subsets (0) | 2020.07.12 |
💯 Daily LeetCode Challenge Day_10 - Flatten a Multilevel Doubly Linked List (0) | 2020.07.10 |
💯 Daily LeetCode Challenge Day_09 - Maximum Width of Binary Tree (0) | 2020.07.09 |
댓글