KBD

Keith Devens .com

Saturday, July 19, 2008 Flag waving
Man up! – Justin
← 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)
:

July 2008
SunMonTueWedThuFriSat
 12345
6789101112
13141516171819
20212223242526
2728293031 



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

Spider solitaire

To answer an earlier question, I am​almost certain every game can be​beat. ...

Jared: Jul 16, 2:20pm

I hate Norton Antivirus

I HATE NORTON ANTIVIRUS IT SUCKS I​GOT AVG IT ROX! AGES TO DELETE​NORTON AN...

wade: Jul 15, 1:44am

Girls, please don't get breast implants

Girls,

   Lots of guys enjoy​smaller breasts.  Several years ago​a well-...

j: Jul 13, 10:13am

Generated in about 0.138s.

(Used 8 db queries)

mobile phone