1

I'm trying to reverse a large integer (>100 digits). I wish to implement it in such a way that the trailing zeroes in the original number are neglected. ie: reverse(2130200) gives 20312. My question is, how to implement reverse() in such a way that the trailing zeroes in the large integer are not added neglected. Eg: reverse(20301205500) gives 550210302

This is the code I implemented for small values.

#include <iostream>
using namespace std;

int myreverse(int num)
{
    int rev=0;
    while(num)
    {
        rev=rev*10+(num%10);
        num/=10;
    }
    return rev;
}

int main()
{
    int num;
    cin>>num;
    int a1 = myreverse(num);
    cout<<a1<<endl;
    return 0;
}
7
  • 1
    int can't hold a number with 100 digits. Why don't you operate on strings?
    – Blender
    Jul 2, 2014 at 14:46
  • 4
    If it's over 100 digits, use a std::string, std::reverse, and find_last_not_of.
    – chris
    Jul 2, 2014 at 14:47
  • 1
    Thanks @chris! But I would like to implement the logic without just using 'reverse() method available in stl'. Jul 2, 2014 at 14:48
  • 1
    Okay, then make your own reverse function taking those iterators and sub it in.
    – chris
    Jul 2, 2014 at 14:49
  • 1
    Are you planning to do any arithmetic operations on this number after reversing it? If not, then as @chris has mentioned, you might as well use std::string. But if you are planning to perform arithmetic operations on it, then you'll need to use some sort of "BigInteger" class. You can see an example of such class in here: github.com/barakman/Num. Jul 2, 2014 at 14:52

1 Answer 1

0

Look at this code, i hope it will help you:

#include <iostream>

using namespace std;

int main()
{
    int number = 1234567890;

    cout << "Number: " << number << endl;

    string str_of_number = to_string(number);

    string rvsd_str_of_number(str_of_number.rbegin(), str_of_number.rend());

    int rvsd_number = std::atoi(rvsd_str_of_number.c_str());

    cout << "Reversed number: " << rvsd_number << endl;
}

Output:

Number: 1234567890
Reversed number: 987654321

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.