LeetCode 8-9 Solutions
2018-01-01 21:55
295 查看
8. String to Integer(atoi)
class Solution { public: bool isDigit(char c) { return c >= '0' and c <='9'; } int myAtoi(string str) { size_t idx = 0; size_t len = str.length(); int sign = 1; double val = 0; for (size_t i = 0; i < len; ++i) { // 1st none white space character if (str[i] == ' ') ++idx; else break; } // while (str[idx] == ' ') ++idx; if (idx == len) return 0; // sign(followed by integeral characters) if (str[idx] == '+') { sign = 1; if (!isDigit(str[++idx])) { return 0; } } else if (str[idx] == '-') { sign = -1; if (!isDigit(str[++idx])) { return 0; } } for (; idx < len; ++idx) { if (!isDigit(str[idx])) break; val = (str[idx] - '0') + val * 10; } val *= sign; if (val > INT_MAX) return INT_MAX; else if (val < INT_MIN) return INT_MIN; else return val; } };
this code can pass all the testcases, but has ugly style. One should pay attention on the type of
val,
long longor
unsigned long longwill fail on some testcases. And I still haven’t figured out the reason.
9. Palindrome Number
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; int _x = x, y = 0; while (x) { y = y * 10 + x % 10; x /= 10; } return _x == y; } };
this solution can pass all the testcases, but may has problem on (reversed)integer overflow(say input number is 1463847418), and used two extra space.
相关文章推荐
- 【LeetCode】162. Find Peak Element (3 solutions)
- 【LeetCode】130. Surrounded Regions (2 solutions)
- 【LeetCode】13. Roman to Integer (2 solutions)
- 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)
- 【LeetCode】217. Contains Duplicate (2 solutions)
- 【LeetCode】115. Populating Next Right Pointers in Each Node (2 solutions)
- 【LeetCode】111. Minimum Depth of Binary Tree (2 solutions)
- 【LeetCode】Valid Anagram (2 solutions)
- LeetCode Solutions : Find Minimum in Rotated Sorted Array
- 【LeetCode】215. Kth Largest Element in an Array (2 solutions)
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree (2 solutions)
- 【LeetCode】102. Binary Tree Level Order Traversal (2 solutions)
- 【LeetCode】32. Longest Valid Parentheses (2 solutions)
- 【LeetCode】48. Rotate Image (2 solutions)
- 【LeetCode】3. Longest Substring Without Repeating Characters (2 solutions)
- 【LeetCode】4. Median of Two Sorted Arrays (2 solutions)
- 【LeetCode】14. Longest Common Prefix (2 solutions)
- 【LeetCode】142. Linked List Cycle II (2 solutions)
- 【LeetCode】50. Pow(x, n) (3 solutions)
- 【LeetCode】12. Integer to Roman (2 solutions)