Chewbacca and Number, Hackerblocks Tutorial

I have understood the problem but I am not able to understand the code through the video.
Can you please explain me the code.

1 Like

Hey @avijuneja2007
In the code, we’re storing the number in a character array
Let me explain the parts of the code:

int i = 0;
if(a[i] == '9'){
i++;
}

See basically if first digit is 9(the first element of the string is β€˜9’), we don’t have to invert it coz answer can’t start with a zero. (we don’t have to reduce no of digits in the given number).
Now for the further digits, we invert them(subtract the digit from 9) if they are greater than 5, coz we’ve to find the minimum possible number. and inverting the digits larger than 5 will result in smaller digit and hence smaller resultant number.

for( ; a[i]!=’\0’; i++){
int digit = a[i]-β€˜0’;
if(digit >= 5){
digit = 9-digit;
a[i] = digit+β€˜0’;
}
}

So for every element of the array, we find the digit from the character by subtracting β€˜0’ (coz we need int and β€˜3’-β€˜0’ will give us 3). Then we invert the digit if it’s greater than 5, and then convert the digit back to character(β€˜0’+3 will give us β€˜3’) and store it in the array.

2 Likes

So, basically what you are trying to say is that if we take the a[i] as 5 , then according to ASCII table , the value corresponding to the char 5 is 53 and we need to subtract char 0 from it having a corresponding value of 48 inorder to convert it into int. Like β€˜5’-β€˜0’ means 53-48? Am I saying right?

@avijuneja2007 yeah right

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.