| Author |
[easy]Most Significant Bit
|
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
|
|
This is rather trivial, but I'm curious to see whether or not anyone has any interesting approaches to this. I also thought I would throw in an actual programming diversion for a change as well. The problem: give an input long integer (let's assume positive, but I'd also be interested in discussing the ramifications if any of considering negatives), return the position of the long's most significant bit (MSB). For ease, I guess we can keep the count zero-based. Therefore, if we want the MSB of 7, the answer would be 2. The leftmost one bit, the MSB, is in the 2^2 position, so the MSB of 7 is 2.
|
Jason's Blog
|
 |
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
|
|
How's this for quick and dirty. [ August 26, 2003: Message edited by: Carl Trusiak ]
|
I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
|
 |
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
|
|
Not too shabby. For a more general solution, although probably not the best, here's what I came up with.
|
 |
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
|
|
Not bad, however for negitive numbers your routine returns 0 (OK, he did say may include negatives) However for large numbers such as Integer.MAX_VALUE it goes into an infinite loop. Hows' this: Now for 0 it returns -1 Where the String version returns 0 but, he did specify what that should return so, I guess both answers are correct As the saying goes, no Specification, no Bug!
|
 |
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
|
|
Pretty good. I've got a special place in my heart for bit operations. I guess there's something to be said for actually testing code, eh?
|
 |
 |
|
|
subject: [easy]Most Significant Bit
|
|
|