Lets say the input is 19
.
The first iteration of the outer loop will make sum
equal to 10
, and sets s
to "10"
.
The second iteration of the outer loop (when s
is "10"
) will add 1
(and 0
) to sum
, making it equal to 11
, so when the inner loops end then s
becomes "11"
.
The third iteration of the outer loop will add 2
(1
and 1
) to sum
, so sum
becomes 13
and s
becomes "13"
.
And so on forever.
The length of s
will never become equal to (or smaller than) 1
. And that leads to an infinite loop. Which will likely be stopped by the online system due to a timeout.
I haven't read the problem description (in the future please include it in the question, to make your questions self-contained) but your algorithm is wrong, and you need to rethink your solution. Very likely you should reset sum
(i.e. sum = 0;
) before the inner loop, or better yet define it inside the inner loop:
int x,count=0;
string s; cin>>s;
while(s.length()>1){
int sum = 0;
for(int i=0;i<s.length();i++){
x=s[i]-'0';
sum+=x;
}
s=std::to_string(sum);
count++;
}
[I reasoned me to this by doing rubber duck debugging of the code]