Leetcode Note: Reverse Integer

Source: Internet
Author: User

Leetcode Note: Reverse Integer

I. Description

Reverse digits of an integer.

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

Ii. Question Analysis

Returns an integer. If it is a negative number, the negative number remains unchanged, and then the negative number is reversed. This question is simple, but it hides some traps, such as the overflow problem of the number after the reversal, and how to deal with it when the low position is 0 and the reverse is to the high position. The purpose of this question is not to examine an algorithm, but to check whether all kinds of boundary conditions are well considered. The code here is only Accept, which does not mean perfect.

Iii. Sample Code

Class Solution {public: int reverse (int x) {long result = 0; const int max = 0x7fffffff; // int maximum value const int min = 0x80000000; // int minimum value for (; x! = 0; x/= 10) {result = result * 10 + x % 10; if (result> max | result <min) result = 0; // beyond the 32-bit int range, set 0} return result ;}};

Iv. Summary

For some seemingly simple questions, the more you need to consider some boundary conditions, and these can also bring you extra points during the written examination or interview.

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.