Ciel and A-B Problem

Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not allowed. If there are multiple answers satisfying the above conditions, anyone will do

#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
if(a-b==9||a-b==99||a-b==999||a-b==9999||a-b==99999)
printf("%d",a-b-1);
else
printf("%d",a-b+1);
}

i am not able to find the input for which the code fails

1 Like

Try with following input:

318 109

Your code prints 210. The actual difference is 209. However, the problem says the output should have EXACTLY ONE digit different from the correct answer. But you have two digit difference.

Problem with your logic is you are expecting the difference to be only 9,99,9999, etc. and if it is not, then you are incrementing the last digit by 1 in order to get 1 digit difference. However, in doing so you are ignoring all those cases where the last digit is 9 but rest of the digits are not 9. So your whole intension of getting into the first if block fails and you went on incrementing rather than decrementing.

A simple way to cover such cases is to just check the last digit of difference. If it is 9, you decrement the difference else you increment. Check below version of your code:

#include <stdio.h>

int main() { 
    int a,b; 
    scanf("%d %d",&a,&b); 
    
    if((a-b)%10==9) printf("%d",a-b-1); 
    else printf("%d",a-b+1); 
    
    return 0;
}
4 Likes

In 210 and 209 there is difference of only one digit i.e 1&9. So,210 is an acceptable answer.
Output details
The correct answer of 5858-1234 is 4624. So, for instance, 2624, 4324, 4623, 4604 and 4629 will be accepted, but 0624, 624, 5858, 4624 and 04624 will be rejected.

You are getting it completely wrong then. Please read the question once again. Here you have two digits difference. One between 1 and 0 in the tenths place and another between 0 and 9 in the units place, even though the actual difference is just 1. You are allowed to have only one digit difference.

3 Likes

Thanx, i got my mistake