0

I was doing this exercise : https://www.hackerrank.com/challenges/30-binary-numbers/problem and I found this code, but I didn't understand what the condition with n&1 and n>>=1 do here.

 //C++ program to convert a decimal
// number to binary number

#include <iostream>
using namespace std;

int main()
{
    int n,count=0,max=0;
    cin >> n;

    while(n)
    {
        if (n&1)
            count++;
        else
            count = 0;
        if (max < count)
            max = count;
        n>>=1;
    }
    cout << max;

    return 0;
}
mkx
  • 3
  • 4
  • Sorry to be that guy, but duplicate of https://stackoverflow.com/questions/38922606/what-is-x-1-and-x-1 EDIT: @t.niese got it a second before me :) – Bobbbay Aug 07 '20 at 17:09
  • [What is (x & 1) and (x >>= 1)?](https://stackoverflow.com/questions/38922606/what-is-x-1-and-x-1) – t.niese Aug 07 '20 at 17:09
  • They are operators. –  Aug 07 '20 at 17:10
  • 2
    You shouldn't use hackerrank or similar sites to learn a programing language. Instead, you should consider to use a good [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn the basics of the language. – t.niese Aug 07 '20 at 17:11

2 Answers2

1
if (n&1)

checks whether n is odd by doing a bitwise and.

n>>=1;

shifts the bits of n to the right by one bit.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 1
    Detail: `if (n&1)` incorrectly tests for odd-ness on those long forgotten [1s' complement](https://en.wikipedia.org/wiki/Ones%27_complement) machines when `n < 0`. Not a real concern in 2020. – chux - Reinstate Monica Aug 07 '20 at 17:16
0

The & is a bitwise-AND operator and evaluates the expression in either true or false (when the expression is conditional), it's pretty much similar to x % 2, i.e. this condition:

if (n & 1) {
    //...
}

// is equal to

if (n % 2) {
    // ...
}

OTOH, n >>= 1 shifts right n by a bit.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • "it's similar to x % 2 which obviously returns either 1 or 0 as remainder" --> `x%2` returns 0, 1 or -1. – chux - Reinstate Monica Aug 07 '20 at 17:14
  • `The & is a bitwise-AND operator and evaluates either true or false` this is highly misleading, a bitwise operator does not evaluate to true or false. If you have `01111 & 01001` it will evaluate to `01001`. If the result of the `&` is used in an `if` then this result itself will be evaluated to a boolean. – t.niese Aug 07 '20 at 17:14
  • @t.niese updated, Thanks. – Rohan Bari Aug 07 '20 at 17:19