"Leetcode" Reverse Integer Go language implementation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Problem description

Reverse digits of an integer.

EXAMPLE1:X = 123, return 321
example2:x = -123, return-321

The test instructions is very clear and reverses an integer output.

Ideas

First of all, it is not an algorithm to consider the way that library functions first convert to string inversion.
The overall solution to the idea is to take out each number of integers in turn, then reverse, then assemble into integers. There are several points to consider:

    • Take the lowest number. num % 10can be.
    • Remove the bottom number. num / 10can be.
    • Assemble integers. Define sum := 0 , loop the number sequence, each time sum = sum * 10 + 数字 you can
    • Overflow problem. The problem specifies that the integer is 32 bits, so the maximum value is 0x7FFFFFFF , the minimum value is-0x80000000

Go implementation

Spents 6ms, beat 20% people with Golang.

var MINint=0x80000000var MAXint=0x7FFFFFFFFuncReverse(xint)int{sum:=0     for{leftdigits: = x/TenLastdigit: = x%Tenx = Leftdigitssum=sum*Ten+ Lastdigitif 0= = Leftdigits { Break}    }if sum<-min | |sum> MAX {fmt. Println (sum)sum=0}return sum}
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.