LC 9
Determine whether an integer is a palindrome. Do this without extra space.
如何获得最后一位:x % 10
如何获得除了最后一位的数 x/10
如何把一个数字y加到末尾:x*10+y
没看答案之前没有什么特别好的想法,看了之后学会了一个构造某个数值的反向序列的方法:
递归地获取最后一位(%10),并把最后一位加到反向序列的末尾(rev = rev*10+last_digit)),去掉最后一位(x = x/10)。
class Solution {
public:
bool isPalindrome(int x) {
if (x<0) return false;
if (x!=0 && x%10 == 0) return false;
int rev = 0;
while (x > rev) {
int last_dig = x%10;
x = x/10;
rev = rev*10+last_dig;
}
if (x == rev|| x==rev/10) return true;
return false;
}
};
在这里补充一道题:
LC 7 reverse integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这道题和上面的题基本上同样的做法,只不过需要额外符号以及考虑new_ans = ans*10+last_digit溢出的情况。
溢出的判断是ans == (new_ans-last_digit)/10
class Solution {
public:
int reverse(int x) {
int sign = x < 0? -1: 1;
x *= sign;
int ans = 0;
while (x) {
int last_dig = x%10;
int tmp_ans = ans * 10 + last_dig;
if (ans!=(tmp_ans - last_dig)/10) { // handle overflow
return 0;
} else {
ans = tmp_ans;
}
x = x/10;
}
return ans * sign;
}
};
LC 234 Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
这道题思路很简单,实现起来需要考虑的细节很多。思路:把前一半的链表反转,从中间开始向两边遍历。
首先这道题需要熟练地背出反转链表的解法。然后用双指针的办法找到链表的中点。
这道题思路上没有什么难点,主要是考实现细节。所以一定要注意写算法题的7个步骤,并记忆、程序化。
AC代码:
class Solution {
public:
bool check(ListNode * h1, ListNode*h2) {
while (h1 && h2) {
if (h1->val != h2->val) return false;
h1 = h1->next;
h2 = h2->next;
}
return h1 == h2;
}
ListNode * reverseList(ListNode* head, ListNode* stop) {
// assuming no nullptr along the list
ListNode * prev = nullptr, *cur = head, *next = head;
while (cur != stop) {
next = cur -> next;
cur -> next = prev;
prev = cur;
cur = next;
}
return prev;
}
bool isPalindrome(ListNode* head) {
if (head == nullptr || head->next == nullptr) return true;
ListNode* slow = head, * fast = head;
while (fast && fast->next) {
slow = slow -> next;
fast = fast->next->next;
}
if (fast == nullptr) { // even nodes
return check(reverseList(head, slow), slow);
} else { // odd nodes
return check(reverseList(head, slow), slow->next);
}
}
};d