-5
#include<cstdio>
using namespace std;
char s[11];
int main()
{
    int n=0,a;
    scanf("%s",s);
    for(a=0;s[a];++a) {
        n=2*n+(s[a]==55);
        printf("%d ",n);
    }
    printf("%d\n",n-1+(1<<a));
}

In this code I've found difficulty to understand the line n=2*n+(s[a]==55);. Particularly s[a]==55.Please tell me how it works?

Ayon Nahiyan
  • 2,140
  • 15
  • 23

2 Answers2

2

Just as in an if statement, s[a] == 55 evaluates to true if the byte s[a] equals 55; otherwise, it's false. That's it.

The true or false value will then be converted into 1 or 0 (respectively) for the addition to 2*n.

Of course it almost goes without saying that this code is dreadful and should not be used. The variables have non-descriptive names and there is a grand total of zero comments explaining what is going on and why.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Thank you for your answer. Since it was coded in a programming contest that's why the contestant coded it without descriptive names and comments. – ashap_bappy May 08 '17 at 20:38
  • @ashap_bappy: What sort of contest was it? A contest to see who can make the worst code? How pointless. – Lightness Races in Orbit May 08 '17 at 20:48
  • It was in a Codeforces regular round contest. As you know in competitive programming how fast you can write your accepted code that is matter. It doesn't matter how you write your code. :) – ashap_bappy May 08 '17 at 20:57
  • 1
    Yeah, may be that's why competitive programmer often struggle in their job life because of writing reckless code. – ashap_bappy May 08 '17 at 21:01
  • @ashap_bappy: Probably :) – Lightness Races in Orbit May 08 '17 at 21:05
  • @BoundaryImposition You know that SE has an entire site devoted to programming contests like this. It's called Code Golf, and the judging criteria is often how few characters are used in the solutions. – Barmar May 08 '17 at 21:24
  • @Barmar: Yes, I am fully aware of their existence. They are silly. – Lightness Races in Orbit May 08 '17 at 22:42
  • @BoundaryImposition You might as well ask why people run marathons, when they could easily drive. – Barmar May 08 '17 at 23:43
  • @BoundaryImposition The basic idea is that Code Gold is not an exercise in practical programming, it's just a way to see how clever you can be. It's no sillier than playing video games. I don't do either, but I can see how participants would find them fun. – Barmar May 08 '17 at 23:51
  • @Barmar: Oh I can certainly see why it would be fun. Never claimed otherwise! – Lightness Races in Orbit May 08 '17 at 23:53
2
n=2*n+(s[a]==55);

is a cryptic way of writing:

if ( s[a] == 55 )
{
   n = 2*n + 1;
}
else
{
   n = 2*n;
}     
R Sahu
  • 204,454
  • 14
  • 159
  • 270