int fncSpecialBinary(int n){
int l,r;
l=n<<1&~n;
r=n&~n<<1;
return(r&(l|-l));
}

0

Marcos Freitas de MoraisCommented:

All you need is a code to search the pattern: { 1, 0, ..., 1 } with a quantity of zeros varying from 1 to n.

0

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

// further simplifying:
int fncSpecialBinary(int n){
return ~n&-n&n>>1;
}

0

kevinvw1Author Commented:

Rgonzo1971... nope, not my homework. If your username is any indication of your age, I am older than you and have not been in school since the 80s. :)
But since you went there...
Your answer works good for an Introduction to Programming 101 Junior college course.
But Ozo's answer is definitely Grad School material.

0

Marcos Freitas de MoraisCommented:

I thought about signed signed numbers, precisely ones' complement and I wanna post some comments about accepted solution.

If we use this algorithm by ones' complement for number 4, we have something like:

(~4 & 11 & 4>>1) // 11 is negative value to 4 and this sentece return true

mccarlIT Business Systems Analyst / Software DeveloperCommented:

@DiSalomao,

I think you are confusing your 'ones' and 'twos' complements. -n gives you the *twos* complement of n, ie. if n is 4 (and if we are talking 4-bit numbers as in your example) then -n is 12 (not 11)... and the result evaluates to false which is correct!

0

Marcos Freitas de MoraisCommented:

Mccarl,

There is no mistakes. I have a x86 machine and for me the accepted solution works fine, too. Why ? My computer donĀ“t use ones' complement to represent negative numbers.

But, if you get the code {... return ~n&-n&n>>1;...} and compile on computers that use ones' complement to represent their negative numbers, you'll get a bug. By the way, on that kind of machines -4 (decimal) == 1011 (binay) == 11 (unsigned decimal).

I just propose my code, because it's more portable one and to justify my comments.

The C language standard does allow for ones complement or sign/magnitude representation, although I'm not familiar with any computer architecture that's used them since the 1960's
If you are running on such a computer, you can use
unsigned int fncSpecialBinary(unsigned int n){
return ~n&(~n+1)&n>>1;
}

0

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Basically, you should do your homework alone

Here is my pseudo-code

Open in new window

Regards