LeetCode # Reverse Number #

Source: Internet
Author: User

LeetCode # Reverse Number #

 

LeetCode # Reverse Number #

 

 

I just memorized the word and made a question to play with it ~ Pick a soft persimmon and step on it ~ Haha

 

It's a simple idea, but the fun thing is that I forgot to check whether the processed data conforms to the integer data and returned it. So I can't AC for a while.

Thanks @ Fantasy. I quickly pointed out that I did not check the returned data range.

 

First, I will give a very ugly solution (python), and then give a very elegant solution from other experts !! Python is also used.

Finally, we will provide solutions using java and C/C ++.

 

 

Programmer : EOFDate : 2015.03.31File   :  reverse_interger.pyclass Solution:    # @return an integer    def reverse(self, x):buffer =[]INT_MAX = 0x7fffffffINT_MIN = (-INT_MAX - 1)if x > INT_MAX or x < INT_MIN :    return 0if x > 0 :tmp = xcounter = 1while tmp > 0 :counter += 1buffer.append(tmp % 10);tmp /= 10tmp = 0for i in range(0, len(buffer)) :tmp *= 10tmp += buffer[i]if tmp > INT_MAX or tmp < INT_MIN :return 0    return tmpelif x < 0 :tmp = -xcounter = 1while tmp > 0 :counter += 1buffer.append(tmp % 10);tmp /= 10tmp = 0for i in range(0, len(buffer)) :tmp *= 10tmp += buffer[i]if tmp > INT_MAX or tmp < INT_MIN :return 0        return -tmpelse:return 0#--------------------------just for testing ----------------------------s = Solution()print s.reverse(123)


 

... It is really easy to do a basic mathematical operation, using the remainder and quotient features, the results are saved in the list. then, combine them into integers in reverse order. Finally, do not forget to re-check whether the integer meets the requirements and whether it is out of bounds !!

 

The following provides an elegant solution for others:

 

class Solution:  # @return an integer  def reverse(self, x):    if x<0:      sign = -1    else:      sign = 1    strx=str(abs(x))    r = strx[::-1]    return sign*int(r)

It cannot be shorter.

 

First, convert the string into a string, and then use the python Slicing Technique to output characters in reverse order, and then use int () to forcibly convert to limit the Integer Range.

The last data recovery symbol.

 

Java solution (from @ Kaixuan chongfeng): utilizes the built-in shaping feature

 

package reverse_integer;public class Solution {public int reverse(int x) {long r = 0;while (x != 0) {r = r * 10 + x % 10;x /= 10;}return r > Integer.MAX_VALUE || r < Integer.MIN_VALUE ? 0 : (int) r;}public static void main(String[] args) {System.out.println(new Solution().reverse(1563847412));}}


 

Finally, I offered my answers and implemented them in C language.

I slapped myself and rubbed it. I didn't see the notes written by Hao !!

 

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,
 

 

 

// Source : https://oj.leetcode.com/problems/reverse-integer/// Author : Hao Chen// Date   : 2014-06-18/********************************************************************************** * * Reverse digits of an integer.* * Example1: x =  123, return  321* Example2: x = -123, return -321* * * 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).* *               **********************************************************************************/#include 
 
  #include 
  
   //Why need the INT_MIN be defined like that?//Please take a look: //  http://stackoverflow.com/questions/14695118/2147483648-0-returns-true-in-c#define INT_MAX     2147483647#define INT_MIN     (-INT_MAX - 1)int reverse(int x) {    int y=0;    int n;    while( x != 0){        n = x%10;        //Checking the over/underflow.        //Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it.        if (y > INT_MAX/10 || y < INT_MIN/10){             return 0;        }        y = y*10 + n;        x /= 10;    }    return y;}#define TEST(n, e)  printf(%12d  =>  %-12d    %s!,  n, reverse(n),  e == reverse(n)?passed:failed)int main(int argc, char**argv){    //basic cases    TEST(  123,  321);    TEST( -123, -321);    TEST( -100,   -1);    TEST( 1002, 2001);    //big integer    TEST( 1463847412,  2147483641);    TEST(-2147447412, -2147447412);    TEST( 2147447412,  2147447412);    //overflow    TEST( 1000000003, 0);    TEST( 2147483647, 0);    TEST(-2147483648, 0);    //customized cases    if (argc<2){        return 0;    }    printf();    for (int i=1; i  %-12d    %s!,  n, reverse(n), reverse(reverse(n))==n ? passed:failed);    }    return 0;}
  
 


 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.