1. 程式人生 > >7. Reverse Integer

7. Reverse Integer

its flow abcd subst poi reverse ber input leetcode

7. Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

 1 /**
 2  * @param {number} x
 3  * @return {number}
4 */ 5 var reverse = function(x) { 6 //翻轉問題對於我而言直接想到的就是分治遞歸。 7 8 //比如ABCD 9 //先 CDAB 10 //在 CD 轉成 DC AB轉成BA 11 12 13 14 function innerReverse(x){ 15 //處理負數 16 var flag = ""; 17 18 //先轉成字符串 19 x = "" + x; 20 21 var len = x.length; 22 23 if
(len <= 1){ 24 return x; 25 } 26 27 //轉成number判斷正負 28 if(+x < 0){ 29 flag = "-"; 30 x = x.substring(1,len); 31 } 32 33 var mid = Math.floor((len - 1) / 2); 34 35 var pre = innerReverse(x.substring(mid+1,len)); 36 var suf = innerReverse(x.substring(0,mid+1));
37 38 39 var res = flag ? "" + flag + pre + suf : ""+ pre + suf; 40 return res; 41 } 42 43 44 var res = +innerReverse(x); 45 //這題一開始沒管越不越界,其實js是可以越界的,但是沒辦法,要兼容其它語言,所以我們不要超過int的最大位,當然這個問題我在開始就判斷了,後來發現,其實一開始可以不超過的,但是反轉了就超過了,所以要在結尾判斷。 46 return Math.abs(res) > Math.pow(2, 31) - 1 ? 0 :res ; 47 48 };

7. Reverse Integer