[LeetCode]#9 Palindrome Number

一、题目

Determine whether an integer is a palindrome. Do this without extra space.

 

二、解析

本题的意思是给出一个数字,判断他是否是回文数字。注意,负数不是回文,例如-12321,从左到右是-12321,从右到左是12321-。

我的做法是将数字转化成字符串,给一个头指针和一个尾指针,比较二者的值。若相等,头指针向右+1,尾指针向左-1。

后来又试了试利用数学的方法做,即将原数字%10存储,得到的数字按数字规则再重新组成一个新的整形数,看新的数字和旧的数字是否相同。

比较发现,第一种做法耗时252ms,第二种296ms,说明Python在处理字符串的效率要比处理计算的效率高一些。

 

三、代码

1.转换成字符串

 1 class Solution:
 2     # @param {integer} x
 3     # @return {boolean}
 4     def isPalindrome(self, x):
 5         
 6         #switch num to str
 7         if x >= 0:
 8             s = str(x)
 9         else:
10             return False
11         
12         #head, tail compare
13         head = 0
14         tail = len(s) - 1
15         while(head < tail):
16             if s[head] == s[tail]:
17                 head += 1
18                 tail -= 1
19             else:
20                 return False
21                 
22         #compare complete successfully which tells x is a palindrome number.
23         return True

 

2.数学方法

 1 class Solution:
 2     # @param {integer} x
 3     # @return {boolean}
 4     def isPalindrome(self, x):
 5         num = x
 6         lis = []
 7         
 8         #positive go, negitive false
 9         if x < 0:
10             return False
11         else:
12             
13             #get each number of x
14             while num > 0:
15                 lis.append(num % 10)
16                 num = num / 10
17                 
18                 
19             #write x from end to start
20             y = 0
21             count = 0
22             for i in range(len(lis)-1, -1, -1):
23                 y = 10 * y + lis[count]
24                 count += 1
25             
26             if x == y:
27                 return True
28             else:
29                 return False

 

四,总结

1.刷题有一段时间了,都说Python效率低,其实不然。一般的题目都有一个规律,即C/C++效率最高,Python其次,至于Java嘛,呵呵呵呵。。。我之所以用Python的原因是不想考虑太多的语言细节,想把精力尽可能的放在算法本身上。先刷一遍之后,用C++再巩固一遍,那就是学习C++啦。

2.有知道Python在处理字符串和数学计算效率的区别,就要亲自去试。直观上觉得数学计算肯定会快啊,其实正好相反。

posted @ 2015-08-10 11:13  面包包包包包包  阅读(128)  评论(0编辑  收藏  举报