Leetcode7--->reverse integer (Reversed integer)

Source: Internet
Author: User

Title: Given an integer, the value after which the integer is reversed;

Example:

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

Problem Solving Ideas:

Here are just a few points to note:

1. If the integer is a negative number,-123, then the reversal is 321, so it is necessary to reverse from the first position instead of the No. 0 position;

2. If the integer For example: 12300, then the reversal is 321, instead of 00321, so after reversal, need to remove the preceding 0;

3. If the integer example is 2147483647, then the reversal is 7463847412 > Integer.max_value, then 0 is returned;

1  Public classSolution {2      Public intReverseintx) {3         Char[] ch =string.valueof (x). ToCharArray ();4         intBegin = 0;5         intFlag = 0;//flag is used to indicate positive or negative numbers .6         intEnd = Ch.length-1;7         if(x < 0) {//Negative number8Flag = 1;9         }TenBegin =Flag; One          while(Begin <end) { A Exchange (CH, begin, end); -Begin + +; -End--; the         } -StringBuffer SB =NewStringBuffer (); -         inti =Flag;
Minus 0 in front of the reversal. - for(; i < ch.length; i++){ + if(Ch[i]! = ' 0 ') - Break; + } A if(Flag = = 1) atSb.append ("-"); -Sb.append (CH, I, ch.length-i); - if(Sb.tostring (). Equals ("")) - return0; - Doubleres =double.valueof (sb.tostring ()); - if(Res > Integer.max_value | | Res <integer.min_value) in return0; - returninteger.valueof (sb.tostring ()); to + - } the Public voidExchangeChar[] ch,intIndex1,intindex2) { * Charc =Ch[index1]; $CH[INDEX1] =Ch[index2];Panax NotoginsengCH[INDEX2] =C; - } the}

Leetcode7--->reverse integer (Reversed integer)

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.