GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — javascript-algorithms/src/algorithms/math/is-power-of-two at master · BrandonWeb/javascript-algorithms

Expand file tree

/

is-power-of-two

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

is-power-of-two

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
__test__
__test__
 
 
README.md
README.md
 
 
isPowerOfTwo.js
isPowerOfTwo.js
 
 
isPowerOfTwoBitwise.js
isPowerOfTwoBitwise.js
 
 

README.md

Outline

Is a power of two

Given a positive integer, write a function to find if it is a power of two or not.

Naive solution

In naive solution we just keep dividing the number by two unless the number becomes 1 and every time we do so we check that remainder after division is always 0. Otherwise the number can't be a power of two.

Bitwise solution

Powers of two in binary form always have just one bit. The only exception is with a signed integer (e.g. an 8-bit signed integer with a value of -128 looks like: 10000000)

1: 0001
2: 0010
4: 0100
8: 1000

So after checking that the number is greater than zero, we can use a bitwise hack to test that one and only one bit is set.

number & (number - 1)

For example for number 8 that operations will look like:

  1000
- 0001
  ----
  0111
  
  1000
& 0111
  ----
  0000    

References

  • GeeksForGeeks
  • Bitwise Solution on Stanford
  • Binary number subtraction on YouTube
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.