< Back to forum

codechef practice problem

this my code for FLOW004 in codechef easy sections PLz see I tested with many inputs and got desired output but it is showing wrong plz guide

#include <iostream>

using namespace std;

int main() { int T; cin>>T; while(T>0){ int N,a; cin>>N;

    a=N%10;
    int b=0;
    if(N<100){
        b=N/10;
    }
   else {



    for (int P=100;N%P!=N;P=P*10){
        int c=N-N%P;
        b=c/P;
   }}

    cout<<a+b<<endl;
    T--;
}


// your code goes here
return 0;

}

Asked by: aj.20u10739 on Sept. 14, 2021, 3:34 p.m. Last updated on Sept. 14, 2021, 3:34 p.m.


Enter your answer details below:


Enter your comment details below:




1 Answer(s)

avatar

Your first if condition is slightly incorrect.
You've tried to keep b=N/10 for N<100 but, let's consider N=4. The sum should be 8. But your code will return 4.

But notice that you can actually cover these cases in your for loop only.
Consider the following structure of your main function.

a=N%10;
int b=a;
for (int P=10;N%P!=N;P=P*10){
    int c=N-N%P;
    b=c/P;
}

cout<<a+b<<endl;

You first initialize the value of b by a only to cover the case when N is single digit. Then you start the value of P by 10 to cover all the digits starting from the digit at tens place. In this way you'll achieve correct answer.
Solution.

mahawarvishal10 last updated on Sept. 15, 2021, 12:51 a.m. 0    Reply    Upvote   

avatar

thank you very much

aj.20u10739 last updated on Sept. 15, 2021, 10:06 a.m.

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.