First and Last Digit Problem Code: FLOW004

can any tell me what wrongs with my piece of code, I mean the given test cases it passes but while submitting it shows wrong answer.

#include
using namespace std;
int sum_of_1_and_last_digit(long long int X)
{
int sum=0,last=0,number=X;
//storing the last digit
last = number%10;
// while loop for calculating the first digit
while(X>0)
{
X=X/10;
if (X/10 == 0)
break;

  }
sum =last+X;
return sum;

}

int main ()
{
int T;
long long int N;
cin>>T;

for(int i=0;i<T;i++)
 {
 	cin>>N;
    cout<<sum_of_1_and_last_digit(N)<<endl;
 }

return 0;
}

what if the number is a single digit number?

please post question link

more easy way is take input number as a string and print ((str[0]-β€˜0’)+(str[str.size() -1]-β€˜0’)) as this will work for single digit also…

1 Like

First of all, thank you for helping me. Now coming to question its working for me below is the snippet link https://ibb.co/d2Kdz7c

1 Like

Here is the question link : https://www.codechef.com/problems/FLOW004

Your given approach is helpful but could you please point me where my logic stuck and below is the output snippet for you reference where it is shown that for single-digit is also giving the right output

Here is a tip : you can convert a string into a number by s-β€˜0’ where s is any character in the string

Do this:

while(X>0){

if(X/10==0) break;
else X=X/10;

}

Or, in one line do sum= n%10+n/(10^floor(log10(n)))

1 Like

if the number is single digit, the first and last number is same so the sum will be twice of that number

1 Like

U can just convert it to string and then its a one line solution:
https://www.codechef.com/viewsolution/37736861

1 Like

Thank you, Rohan.

1 Like

Thank you Aditya

Your welcome!.

:nerd_face:

Then the complexity will be O(1) right?

Yes.
Sorry for late reply.