Hi!
LeetCode 第七道题: Reverse Integer,难度简单。
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321 Example 2:
Input: -123 Output: -321 Example 3:
Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
最近一周家里有急事,先写了一个解法,后面优化。
1 public class Solution {
2 public int Reverse ( int x )
3 {
4
5 int flag = 1 ;
6 if ( x < 0 )
7 {
8 flag = - 1 ;
9 x = - 1 * x ;
10 }
11
12 var str = x . ToString ();
13 var strL = "" ;
14 var strR = "" ;
15 var len = str . Length ;
16 for ( int i = 0 ; i < len ; i ++)
17 {
18 if ( i < len - i - 1 )
19 {
20 if (! string . IsNullOrEmpty ( strL ) || str [ len - i - 1 ] != '0' )
21 {
22 strL += str [ len - i - 1 ]. ToString ();
23 }
24
25 strR = str [ i ]. ToString () + strR ;
26 }
27 else if ( i == len - i - 1 )
28 {
29 strL += str [ i ];
30 break ;
31 }
32 else
33 {
34 break ;
35 }
36 }
37
38 str = strL + strR ;
39
40 var min = - 1 * Math . Pow ( 2 , 31 );
41 var max = Math . Pow ( 2 , 31 ) - 1 ;
42
43 double num = 0 ;
44 for ( var i = 0 ; i < str . Length ; i ++)
45 {
46 num += int . Parse ( str [ i ]. ToString ()) * Math . Pow ( 10 , str . Length - i - 1 );
47 var signNum = flag * num ;
48 if ( signNum > max || signNum < min )
49 {
50 return 0 ;
51 }
52 }
53
54 return flag * int . Parse ( num . ToString ());
55 }
56 }
Gist code
To use, see:Jektify - Doc
Música
Jekyll plugin to generate html snippets for embedding Spotify Musics. To listen to the full song, open your Spotify and start these musics.
Goodbye!
The word of the day!
Put a very powerful message.