今天這道是leetcode的第七題,難度仍是屬於easy.如今我先挑着那些簡單的作了,後面再作那些複雜滴.
題目是這樣的:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!git
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.this
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?code
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.leetcode
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.input
第一種方法是很直白的按照它的思路寫下來:
var reverse = function(x) {string
let sign = x>0 ? 1 : -1; let str = x + ""; let i = str.length-1; while (str[i]=="0" && i!=0) { i--; } let reverseStr = str.substring(0, i+1).split('').reverse().join(''); let reverseX = parseInt(reverseStr); if (reverseX > 2147483647 || reverseX < -2147483647) return 0; return sign*reverseX;
};
最後是能夠經過的,可是耗費的時間不少,上面那種方法有挺多須要改進的地方
如今換另外一種方法.it
var reverse = function(x) { let reversed = 0; while(x) { reversed = reversed * 10 + x % 10; if (reversed > 2147483647 || reversed < -2147483647) return 0; x = parseInt(x/10); } return reversed; };
這是最優的方法,上面那種方法定義變量用let比較好,最初我用的var,後來運行不如let快,別看小小一個地方,let比var快了10%呢,很可觀的進步了.io