Chewbacca and Number

how do I approach chewbacca and Number problem

hello @s.kumar

read a number as string (say s) .
if left most character is β€˜9’

  • then leave the leftmost character as it is and for other characters simpl replace s[i] with min(s[i],β€˜9’-s[i])

else:

  • for each i replace s[i] with min(s[i],β€˜9’-s[i])

print s

#include<bits/stdc++.h>

using namespace std;

int main() {

    string n;

    cin>>n;

    int start=0;

    if(n[0]=='9')

       start=1;

    for(int i=start;i<n.length();i++){

            char c='9'-n[i]+'0';

            n[i]=min(n[i],c );

    }

    cout<<n;

    return 0;

}

why is β€˜0’ added in the following statement,
char c=β€˜9’-n[i]+β€˜0’;

to convert int to char we add β€˜0’ to the number.
here we did that for the same purpose

but both β€˜9’ and s[i] are char only, isn’t it?

…

no, that will be int

β€˜9’ is char, right?
4 is int,
then why β€˜9’-(4+β€˜0’) is giving correct o/p

it will give 5 which is int and not char.

u again need to to add β€˜0’ to convert 5 in to β€˜5’

bro,
n[i]=min(n[i],c); //here n[i] on the right side holds the int value, and c holds char, is it possible to compare char and int?

…

n[i] is char and c is also char.

why is n[i]=min(n[i], β€˜9’-n[i]+β€˜0’) statement not working

for(int i=start;i<n.length();i++){

        //char c='9'-n[i]+'0';

        n[i]=min(n[i],'9'-n[i]+'0' );

}

compiler is treating this -> β€˜9’-n[i]+β€˜0’ as an int .
use char(β€˜9’-n[i]+β€˜0’)

or write ur own min function

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.