标签:
题目:
将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。
给定 x = 123
,返回 321
给定 x = -123
,返回 -321
解题:
直接反转,越界处理好炒蛋
Java程序:
public class Solution { /** * @param n the integer to be reversed * @return the reversed integer */ public int reverseInteger(int n) { // Write your code here int MAX = Integer.MAX_VALUE; if(n>=0){ int res = 0; int num = n; while(n!=0){ if(res>MAX/10) return 0; res =res *10 + n%10; n = n/10; } return res; }else{ int res = reverseInteger(-n); return -res; } } }
总耗时: 16030 ms
Python程序:
还没好,一直Pending,Python不需要处理越界问题
class Solution: # @param {int} n the integer to be reversed # @return {int} the reversed integer def reverseInteger(self, n): # Write your code here flag = False if n<0: n = -n flag = True res = 0 while n!=0: res = res * 10 + n%10; n = n/10 if flag: return -res else: return res
lintcode 容易题:reverse integer 颠倒整数
标签:
原文地址:http://www.cnblogs.com/theskulls/p/4890196.html