By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,022 Members | 856 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,022 IT Pros & Developers. It's quick & easy.

Right and Wrong Outputs.Language C

P: 1
I wrote a program to check the max no. of consecutive 1s in binary form of given decimal no. but sometimes it is given wrong output.
For example if I enter 439 I get 4 as output but correct output is 3.

......................c
Expand|Select|Wrap|Line Numbers
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <assert.h>
  6. #include <limits.h>
  7. #include <stdbool.h>
  8.  
  9. int main(){
  10.     int n,max=0,count=0; 
  11.     scanf("%d",&n);
  12.  
  13.     while(n!=0)
  14.     {
  15.         if(n%2!=0)
  16.          {   
  17.             count++;
  18.         }
  19.  
  20.         else
  21.          {
  22.             if(max<count)
  23.            { 
  24.                 max=count;
  25.                 count=0;
  26.             }
  27.         }
  28.         n/=2;
  29.     }
  30.     if(count>max)
  31.         max=count;
  32.  
  33.     printf("%d",max);
  34.     return 0;
  35. }
........................
Feb 24 '17 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
I suggest you not use n /= 2. This makes n a new number with its own binary representation.

Instead make n an unsigned int to avoid int formatting (like 2's complement for negative numbers).

Then compare each bit individually:

n & 1

which will be true if the right bit of n is a 1 and false otherwise.

Then shift the bits in n to the right by 1 position

n >> 1

then when you n & 1 you are testing the second bit in the original n.

Continue in this manner until you have shfted n right by the number of bits in your unsigned int.
Feb 24 '17 #2

Expert 100+
P: 2,398
Shift right until the result is zero -- that way you don't have to know how many bits are in an unsigned int.
Feb 25 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.