📑
LeetCode 231. Power of Two
Question
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
Code
fun isPowerOfTwo(n: Int): Boolean {
if (n < 1 || 1073741824 < n) return false
if (n == 1) return true
var cur = 1
var shifted = 2
while (shifted <= n) {
shifted = cur shl 1
if (shifted == n) return true
cur = shifted
}
return false
}
基数が2なのでシフト演算でnの値を増やしながら確かめていくと、普通に *=2するよりも 60%ほど速くなった。
Profile
- Runtime: 148 ms
- Memory Usage: 33.3 MB
Discussion