Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Solution] Power of four #343

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[Solution] add solution power of four
srk1nn authored Sep 9, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit f108d723182f1d71f22aba4df027c0e861c4f710
29 changes: 29 additions & 0 deletions Math/PowerFour.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Question Link: https://leetcode.com/problems/power-of-four/
* Primary idea: n must be a power of 2 and count of zero bits before the (only) set bit is even.
* Time Complexity: O(logn), Space Complexity: O(1)
*/

class PowerOfFour {
func isPowerOfFour(_ n: Int) -> Bool {
guard n > 0 else {
return false
}

let isPowerOfTwo = (n & (n - 1) == 0)

guard isPowerOfTwo else {
return false
}

var numberOfZeros = 0
var n = n

while n != 1 {
n = n >> 1
numberOfZeros += 1
}

return numberOfZeros % 2 == 0
}
}