9

how to reverse a number?

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

this is my answer:

public int reverse(int x) {
    int result = 0;
    while(x != 0){
        result = result * 10 + x % 10;
        x = x / 10;
    }
    return result;
}

but when I input 1534236469 , it will output 1056389759 , this is wrong. what do you think about my program? thanks.

Jason Ni
  • 159
  • 1
  • 1
  • 8
  • 1
    unless int is required use string as input. 1. check for the minus sign remove if if present. 2. call string.reverse() 3. add minus sign back if it was removed – Nick Feb 17 '15 at 23:31

12 Answers12

5

One reason your program cannot give the right answer is that you store result in an int but you expect to be able to reverse the number 1534236469. The correct answer would be 9646324351, but that number is greater than the largest possible value of an int so you end up with something else. Try long long or try using input with no more than 9 digits.


Followup: I suggested long long because that will fairly reliably give you an 8-byte integer. You may also get 8 bytes in a long, depending on where you are building your code, but Visual C++ on 32-bit Windows (for example) will give you only 4 bytes. Possibly the 4-byte long will go the way of the 2-byte int soon enough, but at this point in time some of us still have to deal with it.

David K
  • 3,036
  • 1
  • 11
  • 18
3

Jason, You should just change the type from int to long.

   public long  reverse(long x)
    {
        long result = 0;
        while (x != 0)
        {
            result = result * 10 + x % 10;
            x = x / 10;
        }
        return result;
    }
Fery
  • 441
  • 1
  • 4
  • 13
  • 1
    this will not work for a negative number, which is part of the OP's input examples. – aruisdante Feb 17 '15 at 23:22
  • 1
    It also depends on the environment where you run. g++ on 64-bit linux will give you 8 bytes to a `long`, Visual C++ on Win32 will give you 4 bytes. – David K Feb 17 '15 at 23:24
  • if the input number over the long type, I think it should be wrong. how do I catch the overflow, if overflow it returns 0 – Jason Ni Feb 17 '15 at 23:27
  • Jason , may you please explain your issue more? – Fery Feb 18 '15 at 16:09
  • @Fery My issue is when I input 1534236469 , then the result should be 9646324351, but this is overflow for int. so how can I catch the overflow and return 0. thanks. – Jason Ni Feb 18 '15 at 19:55
  • So, you need a program to reverse digits of positive and negative integer number and if the input overflows the integer type, 0 should be returned. Am I right?And and we are assuming the int data type you are working with is a 32-bit signed. – Fery Feb 18 '15 at 21:55
  • @JasonNi: What is the environment you use? – Fery Feb 18 '15 at 22:01
  • @aruisdante : because of definition of % in C#.net, the method works for negative numbers, if you are in same IDE. Check this [link](https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx): – Fery Feb 18 '15 at 22:12
  • Indeed, but the `%` operator behaves differently depending on language. Since they don't specify, it's probably unsafe to assume that `%` will behave as expected for negative values, especially since the independent fix is relatively straight forwards. – aruisdante Feb 18 '15 at 22:50
  • @Fery I'm using Intellij for Java – Jason Ni Feb 18 '15 at 23:02
  • @JasonNi Check [this link](https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow) out. – Fery Feb 20 '15 at 16:20
2

You can write x >0 (doesn't matter though )also after that you have to consider negative numbers , I made that change to your logic as follows (Also use long long to avoid overflow):

      long long reverse(long long x)
      {

           int sign = 1;
           long long ans=0;
           if(x < 0)
             sign = -1;
           x = abs(x);
           while(x > 0)
           {
               ans *= 10;
               ans += x%10;
               x /=10;
           }
           return ans*sign;
      }
sashas
  • 2,320
  • 3
  • 12
  • 31
  • The OP's problem case was a positive number. For positive numbers, your code looks identical to his. Does it produce the correct result on `x=1534236469` ? – jez Feb 17 '15 at 23:15
  • @jez also as OP gave in example a negative number I covered that case – sashas Feb 17 '15 at 23:17
  • Indeed, your solution is correct. It would be helpful if however you pointed out what the difference between yours and the OP's code is. Rather than just given them code with no annotation (you fixed the while bug, and the sign bug). – aruisdante Feb 17 '15 at 23:19
  • David K has got the answer – jez Feb 17 '15 at 23:20
  • @aruisdante sorry wrote the answer in haste , will do so. will make an edit. thanks – sashas Feb 17 '15 at 23:20
  • It also still doesn't account for numbers > maximal size of `int`. If that's a requirement, should use `long` etc (doesn't pass the OP's example case). – aruisdante Feb 17 '15 at 23:22
  • @JasonNi I pointed your mistakes and took aruisdantes advice to edit my answe have a look – sashas Feb 17 '15 at 23:23
  • if(x < 0) sign = -1; x = abs(x); can be if (x<0) { sign = -1;x=-x; } – thang Feb 17 '15 at 23:30
  • can "long long" work in java? I use your code in java , compile error shows up – Jason Ni Feb 17 '15 at 23:31
  • @JasonNi, in java use BigInteger – thang Feb 17 '15 at 23:32
  • http://stackoverflow.com/questions/508630/java-equivalent-of-unsigned-long-long no its for C++ you use long , if its bigger then use strings or BigInteger – sashas Feb 17 '15 at 23:33
  • how do I catch the overflow, if overflow it returns 0 – Jason Ni Feb 17 '15 at 23:46
  • @JasonNi not familiar how it is done in Java, but as everyone else suggested you could use big integer to avoid it – sashas Feb 17 '15 at 23:58
1

How about convert to string and reverse? Quite simple:

   int reverseDigits(int x) {
      String s = Integer.toString(x);
      for (int i = 0; i < s.length() / 2; i++) {
        char t = s[i];
        s[i] = s[s.length() - i - 1];
        s[s.length() - i - 1] = t;
      }
      return Integer.parseInteger(s); // subject to overflow
   }
Schultz9999
  • 7,955
  • 6
  • 43
  • 80
1

can use long type to store the result

public int reverse(int x) {
    long result = 0;
    while (x != 0) {
        result = result * 10 + x % 10;
        x /= 10;
    }
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
        return 0;
    return (int)result;
}
1

This is a question posted on Leetcode and it gives a wrong answer expecting a 0. The clue is that before returning the reversed integer we have to check if it does not exceed the limit of a 32-bit int ie 2^31-1.

Code in Python 3:

class Solution:
def reverse(self, x: int) -> int:
    s=[]
    rev=0
    neg=False
    if x==0:
        return 0
    if x<0:
        x=x* -1
        neg=True
    while x:
        s.append(x%10)
        x=int(x/10)
    i=len(s)
    j=0
    while i:
        rev=rev+s[j]*10**(i-1)
        i=i-1
        j=j+1
    if(rev>2**31-1):
        return 0
    return rev * -1 if neg else rev
Ajay Kumar Ganesh
  • 1,790
  • 1
  • 24
  • 33
Apurva Singh
  • 386
  • 3
  • 14
0

Why not simply do:

while (x)
  print x%10
  x /= 10

with a double sign conversion if the value of x is originally negative, to avoid the question of what mod a -ve number is.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
Ian Davis
  • 21
  • 2
0

You are using int for storing the number whereas number is out of range of int. You have tagged algorithm in this question. So, better way would be by using link list. You can google more about it. There are lot of algorithms for reversing a link list.

Ankita Singh
  • 67
  • 1
  • 5
0

A shorter version of Schultz9999's answer:

int reverseDigits(int x) {
  String s = Integer.toString(x);
  s=new StringBuilder(s).reverse().toString();
  return Integer.parseInt(s); 
}
tsig
  • 138
  • 2
  • 6
0

Here is the python code of reverse number::

n=int(input('Enter the number:'))
r=0

while (n!=0):        
    remainder=n%10
    r=remainder+(r*10)
    n=n//10       

print('Reverse order is %d'%r)
Paul Roub
  • 35,100
  • 27
  • 72
  • 83
0

A compact Python solution is

reverse = int(str(number)[::-1])

If negative numbers are a possibility, then

num = abs(number)          # absolute value of the number
rev = int(str(num)[::-1])  # reverse the number
reverse = -rev             # negate the reverse
0

In JS I wrote it in this way

function reverseNumber(n) {
  const reversed = n
    .toString()
    .split('')
    .reverse()
    .join('');

  return parseInt(reversed) * Math.sign(n);
}
Hovakimyan
  • 392
  • 1
  • 7