1 / 4
Feb 2008

Hi folks,
my solution to ADDREV that got accepted is shown below, I see that the time taken by this is about 0.09 and when I change the line

num *= 10

to

num = (num <

the time taken is reduced to 0.07.

The code is accepted but I see that a majority of people who submitted a solution have managed well within 0.04 and some of the best solutions have fared 0.02 and Csaba has done it in 0.0!

What exactly I am doing wrong? How can I possibly impove this?

I tried using array approach to do away with the problem of division and multiplication that take time but could come only as close as 0.07 and no further.

Could any of you suggest what approaches I should be using and also recommendations for books or Internet resources that deal with efficiency improvement of such problems.

Thanks
Dhrupad

include

unsigned long long ReverseNumber (unsigned long long n)
{
unsigned long long a = 0;
unsigned long long num = 0;
while (n && n%10 == 0) {
n = n/10;
}
while (n) {
a = n%10;
n = n/10;
num *= 10;
num += a;
}

    return (num);

}

int main (void)
{
unsigned long long n, a, b;
unsigned long long i;

    scanf("%lld", &n);

    for (i=0; i <n; i++) {
            scanf("%lld %lld", &a, &b);
            printf("%lld\n", ReverseNumber(ReverseNumber(a) + ReverseNumber(b)));
    }

    return (0);

}

  • created

    Feb '08
  • last reply

    May '08
  • 3

    replies

  • 133

    views

  • 3

    users

25 days later

Did not get a reply on this.

I just wanted to know if I need to think about improving input/output or its the logic that I need to worry about.

Is there a alternative to printf/scanf with which I can improve runnning time of programs?

2 months later

long long is very slow in C++ , you can use int instead of it.
It's faster.

#include <stdio.h> 
int ReverseNumber (int n) 
{ 
int a = 0; 
int num = 0; 
while (n && n%10 == 0) { 
n = n/10; 
} 
while (n) { 
a = n%10; 
n = n/10; 
num *= 10; 
num += a; 
} 
return (num); 
} 
int main (void) 
{ 
int n, a, b; 
int i; 
scanf("%d", &n); 
for (i=0; i <n; i++) { 
scanf("%d %d", &a, &b); 
printf("%d\n", ReverseNumber(ReverseNumber(a) + ReverseNumber(b))); 
} 
return (0); 
}

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 15 8d

Want to read more? Browse other topics in C and C++ or view latest topics.