@Ashgoel: Try this:
bool OnesZerosOnes(unsigned int n)
{
if( !(n & 1) || !(n &= n+1) ) return 0;
n |= n-1;
return !(n & (n+1));
}
Here is how it works:
!(n & 1) is true if the number has trailing zeros.
If the number has trailing ones, n &= n+1 replaces the trailing ones with
zeros.
!(n &= n+1) is true if there are only trailing ones, i.e., the original
number was zeros followed by ones.
n |= n-1 replaces trailing zeros with ones. Thus, if the original number is
ones followed by zeros followed by ones, the zeros have been changed to
ones.
(n & (n+1)) replaces the trailing ones with zeros. If the number is now
zero, the number is valid, otherwise the number is invalid.
Dave
On Tuesday, April 3, 2012 7:00:36 PM UTC-5, ashgoel wrote:
> verify that the bits of a number are in format 1s followed by 0s followed
> by 1s like 1110001 is valid but 100100100 is not
>
> Best Regards
> Ashish Goel
> "Think positive and find fuel in failure"
> +919985813081
> +919966006652
>
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/zBATGHVXUTAJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.