Explanation needed for FLOW004

Problem Link: FLOW004

Testcases:
Input
3
1234
124894
242323

Output
5
5
5

Please explain me,what wrong is with my code:
Code:

 #include <iostream>
using namespace std;

int main() 
{
int t;
cin>>t;
for(int i=0;i<t;i++)
{   unsigned long long n;
    cin>>n;
    int firstdigit;
    int lastdigit=n%10;
    while(n>=10)
    {
        n%10;
        n=n/10;
        firstdigit=n;
    }
    cout<<firstdigit+lastdigit<<endl;
}
	return 0;
}

Custom Input:

8
12345
124894
242323
12345678
123456789
1234567890
12345678901
123456789012

Output:

6
5
5
9
10
1
2
3

So,as you can see I have tried the problem with the given three test cases along with additional 5 inputs
and getting the desired output,but still my code is not getting accepted.Can anyone explain,why so?

//Just see my while loop.//

#include
using namespace std;

int main() {
int T;cin>>T;
int sum,lastdigit,firstdigit;
for(int i=0;i<T;i++)
{
long long int N;cin>>N;

    lastdigit=N%10;
    
    firstdigit = N;
    
    while(N>=10)
    {
        N=N/10;
    }
    
    firstdigit=N;
    
    sum=firstdigit+lastdigit;
    cout<<sum<<endl;
        
    }
}

In while you have to just divide that number untill you gets your first digit.

//Just see my while loop.//

#include
using namespace std;

int main() {
int T;cin>>T;
int sum,lastdigit,firstdigit;
for(int i=0;i<T;i++)
{
long long int N;cin>>N;

    lastdigit=N%10;
    
    firstdigit = N;
    
    while(N>=10)
    {
        N=N/10;
    }
    
    firstdigit=N;
    
    sum=firstdigit+lastdigit;
    cout<<sum<<endl;
        
    }
}

In while you have to just divide that number untill you gets your first digit.

1 Like

do the above change and rest is all right
your output is wrong for single digit no:
ex-7 then in this case according to yur code
last digit is 7 is correct but first digit has no value since you have made while loop for>=10

2 Likes

Thank you!!,I got it and my solution got accepted.

Thank you!I got it now actually my solution was not working for single digit number as pointed out by the below user. i didn’t actually set ‘firstdigit=n’ which resulted in not working for summation of the single digit number(input:7 output: sum=14,but I got the sum as ‘7’ instead.

hey; I tried with the below logic and test cases; still my sol is not accepted. It would be great if anyone let me know where I’m missing.

#include <stdio.h>

int main(void) {
// your code goes here
int t,n,f;
scanf("%d",&t);
while (t–){
scanf("%d",&n);
if(n<10) { printf("%d\n",n); continue; }
else if (n>=10 && n<100) f=n/10;
else if (n>=100 && n<1000) f=n/100;
else if (n>=1000 && n<10000) f=n/1000;
else if (n>=10000 && n<100000) f=n/10000;
else if (n>=100000 && n<1000000) f=n/100000;
else if (n==1000000) { printf("%d\n",1); continue; }

    printf("%d\n",n%10+f);
}
return 0;

}

NOTE: I’m trying to code without using the loop logic.

input:
6
8
12
467
1000
24232
124894