Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
So close...
The following code is supposed to find the largest digit in any given integer. It almost does it perfectly minus the exception—numbers 10000 or 504030201. What I noticed is, it does not accept the first number of these integers for some odd reason. Any ideas? https://code.sololearn.com/c44pFHdg546c/?ref=app
2 Answers
+ 5
For 10000, the loop in your code results in the following:
i = 0, num = 10000, mod = 0, sum = 0, i < num;
i = 1, num = 1000, mod = 0, sum = 0, i < num;
i = 2, num = 100, mod = 0, sum = 0, i < num;
i = 3, num = 10, mod = 0, sum = 0, i < num;
i = 4, num = 1, i > num;
While the iteration for the last digit (or more if the length of a decimal representation of number is 10 or more) a should also be executed.
How to fix it:
1. Use while loop and not for loop. In the condition write either `num != 0` or `num` (still stops iterationg when the result is 0).
2. Replace the second "condition" part of a for loop with the code mentioned before.
I would recommend to use the first way, as it is more relatable to this case and does not require additional variable.
0
Use long int that can manage the overflow
#include <stdio.h>
int main(void) {
long int num, i;
int mod, sum=0;
scanf("%li",&num);
for(i=0; i<=num; i++)
{
mod = num % 10;
if(sum<mod)
{
sum = mod;
}
num /= 10;
}
printf("%i",sum);
return 0;
}