Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

asked 26 Dec '11, 04:36

1337c0d3r's gravatar image

1337c0d3r ♦♦
316218111
accept rate: 0%


int reverse(int x) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int lastDigit = 0;
    int result = 0;
    bool isNeg = x>0? false:true;
    x = abs(x);

    while(x>0)
    {
        lastDigit = x%10;
        result = result*10 + lastDigit;
        x = x/10;
    }

    if(result<0) return -1;

    if(isNeg)
        result *=-1;

    return result;        
}
link

answered 31 Dec '12, 15:49

codingtmd's gravatar image

codingtmd
161
accept rate: 0%

public int reverse(int x){

    // Start typing your Java solution below
    // DO NOT write main() function

    int r = 0;

    while(x != 0) {
        r = r*10 + x % 10;
        x /= 10;
    }
    return r;
}
link

answered 14 Jan, 22:08

splax's gravatar image

splax
112
accept rate: 0%

edited 15 Jan, 07:29

class Solution {
public:
int reverse(int x) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
        bool zheng = (x > 0) ? true : false;
int temp = abs(x);
int res = 0;
while (temp > 0)
{
    res = res*10 + temp%10;
    temp /= 10;
}
if(zheng)
    return res;
else
    return -1*res;
}
};
link
This answer is marked "community wiki".

answered 15 Jan, 02:09

BlackMamba's gravatar image

BlackMamba
2614
accept rate: 0%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • Indent code by 4 spaces.
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×125

Asked: 26 Dec '11, 04:36

Seen: 117 times

Last updated: 15 Jan, 07:29