File tree Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ package golang
2+
3+ /*
4+ Given an integer x, return true if x is a palindrome, and false otherwise.
5+
6+ Example 1:
7+
8+ Input: x = 121
9+ Output: true
10+ Explanation: 121 reads as 121 from left to right and from right to left.
11+ Example 2:
12+
13+ Input: x = -121
14+ Output: false
15+ Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
16+ Example 3:
17+
18+ Input: x = 10
19+ Output: false
20+ Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
21+
22+ Constraints: -231 <= x <= 231 - 1
23+
24+ Follow up: Could you solve it without converting the integer to a string?
25+ */
26+ func isPalindrome (x int ) bool {
27+
28+ if x < 0 || (x % 10 == 0 && x != 0 ) {
29+ return false
30+ }
31+
32+ rev := 0
33+
34+ for x > rev {
35+ rev = rev * 10 + x % 10
36+ x = x / 10
37+ }
38+
39+ return x == rev || x == rev / 10
40+ }
Original file line number Diff line number Diff line change 1+ package golang
2+
3+ import "testing"
4+
5+ func TestFirstIsPalindrome (t * testing.T ) {
6+ input := 1221
7+ result := isPalindrome (input )
8+
9+ if ! result {
10+ t .Errorf (`isPalindrome(%v) = %v expected return %v` , input , result , true )
11+ }
12+ }
13+
14+ func TestSecondIsPalindrome (t * testing.T ) {
15+ input := - 1221
16+ result := isPalindrome (input )
17+
18+ if result {
19+ t .Errorf (`isPalindrome(%v) = %v expected return %v` , input , result , false )
20+ }
21+ }
22+
23+ func TestThirdIsPalindrome (t * testing.T ) {
24+ input := 10
25+ result := isPalindrome (input )
26+
27+ if result {
28+ t .Errorf (`isPalindrome(%v) = %v expected return %v` , input , result , false )
29+ }
30+ }
Original file line number Diff line number Diff line change 11| Problem Number | Tag | URL |
22| -------------- | ------------------------------ | ------------------------------------------------------------------------------------ |
33| 2.go | Linked List | https://leetcode.com/problems/add-two-numbers/ |
4+ | 9.go | Math | https://leetcode.com/problems/palindrome-number |
45| 760.go | Hash table | https://leetcode.com/problems/find-anagram-mappings/ |
56| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
67| 1165.go | Hash table | https://leetcode.com/problems/single-row-keyboard/ |
You can’t perform that action at this time.
0 commit comments