Can't understand this code?

Can someone help me in understanding the following code: -

int r, countIt(int n) {
    while (r += "            2  "[n % 10] & 3, n /= 10);
    return r;
}

I found this code in one of the codefights.com problems, https://codefights.com/challenge/v5Zg8trjoun3PTxrZ/solutions/Aj3ppbhSShixt4nBi

This solution is for counting the number of holes in a number. eg

1111 = 0  
0000 = 4  
1234 = 0  
8888 = 8   

I can’t understand the following things:
1. The logic of this code
2. The comma (,) operator used in the return type of the function 3. Using the [] operator after the line.
4. In general, all the code.

+4
source share
3 answers

I looked at the link you provided. After carefully observing the code, I came to the following conclusion.

int r, countIt(int n) {.....}

int r;
int countIt(int n){.....}

while (r += "            2  "[n % 10] & 3, n /= 10);

:

do{
    r += "           2  "[n % 10] & 3;
    n/=10;
}while(n);

r += "           2  "[n % 10] & 3;

.

  • ++

cout<<"abcde"[2];

c

, , - :

r += "           2  "[n % 10] & 3;

- ,

r += "TAB,SPACE,SPACE,SPACE,SPACE,SPACE,TAB,SPACE,2,TAB"[n % 10] & 3;

, . ASCII TAB 9, 1001. ASCII SPACE 32, 100000.

TAB 3

            1001 & 0011 = 0001    which is 1

SPACE 3

            100000 & 000011 = 000000   which is 0

TAB 1 SPACE 0, ,

do{
    r += "1000001021"[n % 10] & 3;
    n/=10;
}while(n);

n% 10 - n. , , r.

+1

- C-? ?


-, . . ,

int x, y;

int x;
int y;

int r;
int countIt(int n) {...}

, , C, .


, :

do {
  r += "            2  "[n % 10] & 3;
  n /= 10;
} while (n);

n.


r += " 2 "[n % 10] & 3;. n % 10 - n. ( char s), ASCII . , , , , , , ASCII "" . 2 - - ​​ 12, 0 9.

, :

static const int numHoles[10] = {1, 0, 0, 0, 1, 0, 1, 0, 2, 1};
int digit = n % 10;
r += numHoles[digit];

, :

int countIt(int n) {
  // number of holes in digit      0  1  2  3  4  5  6  7  8  9
  static const int numHoles[10] = {1, 0, 0, 0, 1, 0, 1, 0, 2, 1};
  int r = 0;
  do {
    int digit = n % 10;
    r += numHoles[digit];
    n /= 10;
  } while (n);
  return r;
};
+9

, Ascii Table , 0 2 4-6, 2 , , (% 3 % 0b11, a 2 ).

ascii:

int countIt(int n) {
    int r;
    while (r += "1000101021"[n % 10] & 3, n /= 10);
    return r;
}

"0" - "2" - :

int countIt(int n) {
    int r;
    while (r += "! X0) I@*9"[n % 10] & 3, n /= 10);
    return r;
}

, , - .

0

Source: https://habr.com/ru/post/1665531/


All Articles