Right and Wrong Outputs.Language C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinendrarocks
    New Member
    • Feb 2017
    • 1

    Right and Wrong Outputs.Language C

    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
    Code:
    #include <math.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <limits.h>
    #include <stdbool.h>
    
    int main(){
        int n,max=0,count=0; 
        scanf("%d",&n);
        
        while(n!=0)
        {
            if(n%2!=0)
             {   
                count++;
            }
            
            else
             {
                if(max<count)
               { 
                    max=count;
                    count=0;
                }
            }
            n/=2;
        }
        if(count>max)
            max=count;
        
        printf("%d",max);
        return 0;
    }
    ............... .........
    Last edited by Frinavale; Feb 27 '17, 03:13 PM.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Shift right until the result is zero -- that way you don't have to know how many bits are in an unsigned int.

      Comment

      Working...