-
-
Notifications
You must be signed in to change notification settings - Fork 250
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
Add/highest power of 2 #195
base: master
Are you sure you want to change the base?
Conversation
Please, merge it under hacktoberfest |
1 similar comment
Please, merge it under hacktoberfest |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems at least partially redundant with #193:
- Given this, can't I implement
nextPowerOf2(n)
ashighestPowerOf2(n) << 1
, with the exception ofn == highestPowerOf2(n)
being handled specially (not shifting in that case)? - This also goes the other way, so
highestPowerOf2
could be implemented in terms ofnextPowerOf2
as well.
The more general "bit twiddling" primitive between both of these is count leading zeros (clz). What if you just implemented that instead?
|
||
export const highestPowerOf2 = (n: number) => { | ||
let result = 0; | ||
for (let i = n; i >= 1; i--) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This loop seems somewhat sketchy, given that it only reduces n
by one in each iteration. Linear runtime in n
is not acceptable, this should be logarithmic in n
(and thus linear in the number of bits).
Find the highest power of two smaller or equal a given number n