File tree 2 files changed +98
-0
lines changed
2 files changed +98
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 毎日一题 - 9. Palindrome number
2
+
3
+ ## 信息卡片
4
+
5
+ - 时间:2019-07-25
6
+ - 题目链接:https://leetcode.com/problems/palindrome-number/submissions/
7
+ - tag:` Math `
8
+
9
+ ## 题目描述
10
+
11
+ ```
12
+ Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
13
+
14
+ Example 1:
15
+
16
+ Input: 121
17
+ Output: true
18
+
19
+ Example 2:
20
+
21
+ Input: -121
22
+ Output: false
23
+ Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
24
+
25
+ Example 3:
26
+
27
+ Input: 10
28
+ Output: false
29
+ Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
30
+
31
+ Follow up:
32
+
33
+ Coud you solve it without converting the integer to a string?
34
+ ```
35
+
36
+ ## 参考答案
37
+
38
+ 转成字符串方式
39
+ 1 . 负数都是非回文数,10的整数倍不是回文。
40
+ 2 . 将数字转为字符串,再逆序排列字符串。两者比较,相等就是回文数。
41
+
42
+ 直接操作整数方式
43
+ 1 . 复制x到temp;
44
+ 2 . 取temp末尾数字,方式为temp与10的求余;组成新数reverse;
45
+ 3 . 每取完一位,temp缩小10倍并且去掉小数。
46
+ 4 . reverse要` 先扩大十倍 ` 再加上取下来的数
47
+ 5 . 当temp === 0时,表示已经取完;reverse与x比较
48
+
49
+
50
+ 参考JavaScript代码:
51
+
52
+ ``` js
53
+ /**
54
+ * @param {number} x
55
+ * @return {boolean}
56
+ * 转成字符串
57
+ */
58
+ var isPalindrome = function (x ) {
59
+ if (x < 0 ) return false ;
60
+ if (x === 0 ) return true ;
61
+ if (x % 10 === 0 ) return false ;
62
+ let reverse = ' ' ;
63
+ let str = String (x);
64
+ for (let i = str .length - 1 ; i >= 0 ; i-- ) {
65
+ reverse += str[i]
66
+ }
67
+ return str === reverse
68
+ };
69
+
70
+ /**
71
+ * @param {number} x
72
+ * @return {boolean}
73
+ * 不转成字符串
74
+ */
75
+ var isPalindrome = function (x ) {
76
+ if (x < 0 ) return false ;
77
+ if (x === 0 ) return true ;
78
+ if (x % 10 === 0 ) return false ;
79
+ let temp = x;
80
+ let reverse = 0 ;
81
+ while (temp > 0 ) {
82
+ let num = temp % 10 ;
83
+ temp = (temp - num)/ 10 ; // 或 temp = (temp / 10) >> 0,去除小数位
84
+ reverse = reverse * 10 + num
85
+ }
86
+ return x === reverse
87
+ };
88
+ ```
89
+
90
+ ## 优秀解答
91
+
92
+ > 暂缺
Original file line number Diff line number Diff line change @@ -155,3 +155,9 @@ tag:`Linked List`
155
155
tag:` 发散思维 `
156
156
157
157
时间: 2019-07-24
158
+
159
+ ### [ 9.palindrome-number] ( ./2019-07-25.md )
160
+
161
+ tag:` Math `
162
+
163
+ 时间: 2019-07-25
You can’t perform that action at this time.
0 commit comments