HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Adding reversed numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbersreversedadding

Problem

This is my solution to the competitive coding question on SPOJ here. It gives a runtime of 0.24 but the best solutions posted have a 0.0 runtime. How could I possibly achieve better results than this?

#include
#include

using namespace std;

int rev(int num)
{
    int rev_num=0;
    while(num)
    {
        rev_num= rev_num*10 + num%10;
        num/=10;
    }
    return rev_num;
}
int main()
{   
    int n, n1, n2;
    scanf("%d",&n);
    while(n--)
    {
        cin>>n1>>n2;
        cout<<rev(rev(n1)+rev(n2))<<endl;

    }
    return 0;
}

Solution

A faster method would avoid the numeric divisions. Instead, it would load the number in a string (through the sprintf function), reverse the string, and finally recast the string into a number (with the help of the sscanf function).

I'm attaching a function named fastrev which in turn uses an auxilliary function reverse_string. Hopefully, this would improve runtime for large numbers.

char* reverse_string(char *s1, char* s2)
{
    char *p, *q;
    int len = strlen(s1);

    for (p = s1; *p; p++) {
        s2[len-1] = *p;
        len--;
    }
    return s2;
}

int fastrev(int num) {
    static char nbuff[32];
    static char rnbuff[32];
    int rnum;

    sprintf(nbuff, "%d", num);
    reverse_string(nbuff, rnbuff);
    sscanf(rnbuff, "%d", &rnum);
    return rnum;
}

Code Snippets

char* reverse_string(char *s1, char* s2)
{
    char *p, *q;
    int len = strlen(s1);

    for (p = s1; *p; p++) {
        s2[len-1] = *p;
        len--;
    }
    return s2;
}

int fastrev(int num) {
    static char nbuff[32];
    static char rnbuff[32];
    int rnum;

    sprintf(nbuff, "%d", num);
    reverse_string(nbuff, rnbuff);
    sscanf(rnbuff, "%d", &rnum);
    return rnum;
}

Context

StackExchange Code Review Q#54645, answer score: 2

Revisions (0)

No revisions yet.