Kotlin Leetcode - 190. Reverse Bits
題目連接:https://leetcode.com/problems/reverse-bits/
class Solution {
fun reverseBits(n:Int):Int {
}
}
解題思路
這一題考的是位元的操作處理
利用 Kotlin 的 shl
shr
等等位元操作
可以很直觀地解決這一題目
Kotlin 參考解答
點擊展開解答
class Solution {
fun reverseBits(n:Int):Int {
var result = 0
for (i in 0..31)
result = (result shl 1) or ((n ushr i) and 1)
return result
}
}
使用 forEach
的寫法
class Solution {
fun reverseBits(n:Int):Int {
var result = 0
(0..31).forEach {
result = (result shl 1) or ((n ushr it) and 1)
}
return result
}
}
- 回到 leetcode 列表