KBD

Keith Devens .com

Sunday, March 21, 2010 Flag waving
*What in our history together makes you think I'm capable of something like that?* – Owen Wilson's character in Shanghai Knights
← 4by12 » Two EnvelopesSam Ruby: Captcha this! →

Daily link icon Wednesday, May 31, 2006

A couple of solutions...

def isPowerOf2(num):
  return num == 1 or num == 2 or (num%2 == 0 and isPowerOf2(num/2))
def isPowerOf2(num):
  count = 0
  while(num > 0):
    count += num%2
    num >>= 1
  return count == 1

Update: From David, in the comments:

def isPowerOf2(num):
  return (num & (num - 1) == 0)

I've never gotten to do enough bit twiddling to have let me think of that.

← 4by12 » Two EnvelopesSam Ruby: Captcha this! →

Comments XML gif

David Lindquist (http://www.stringify.com/) wrote:

Howza bout:

def isPowerOf2(num):
    return (num & (num - 1) == 0)
∴ David Lindquist | 1-Jun-2006 12:14am est | http://www.stringify.com/ | #9477

Keith (http://keithdevens.com/) wrote:

See, there you go. I suck at bit twiddling. Thanks!

Keith | 1-Jun-2006 9:32am est | http://keithdevens.com/ | #9478

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

March 2010
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 3 posts

Recent comments XML

new⇒Spider solitaire

I to am somewhat addicted to​spending too much time on SS.  I​have been stu...

stupid_horse: Mar 20, 10:34pm

I hate ASP.NET

I hate ASP... I was doing wonders​with PHP, then suddenly one of my​clients...

Johnies: Mar 17, 6:14am

Quantum physics and free will

I knew you were going to say that....

Tom Massey: Mar 15, 9:26pm

Generated in about 0.147s.

(Used 8 db queries)