Leetcode -- 7 Reverse Integer (with the implementation of overflow Integer flip), leetcodereverse

Source: Internet
Author: User

Leetcode -- 7 Reverse Integer (with the implementation of overflow Integer flip), leetcodereverse
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 shoshould 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 can you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Hide Tags: Math


Solution:
(1) separate from the low position of the given number n: int s = n % 10;
(2) perform the equivalent flip operation on the number of splits: sum = sum * 10 + s. To prevent overflow, define the sum type as long.
(3) n/= 10; continue the loop operation
(4) Check for overflow: If sum> Integer. MAX_VALUE | sum <Integer. MIN_VALUE, overflow exists and 0 is returned. If no overflow exists, convert the sum type to int.


The Code is as follows:

Public static int reverse (int n) {// The output result is defined as longlong sum = 0; while (n! = 0) {int s = n % 10; sum = sum * 10 + s; n = n/10;} // prevent overflow operation if (sum> Integer. MAX_VALUE | sum <Integer. MIN_VALUE) {return 0;} return (int) sum ;}

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.