Skip to content

Commit

Permalink
Merge 37d6c0e into 9e29024
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 12, 2019
2 parents 9e29024 + 37d6c0e commit fadea94
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,4 @@ problems from
* [Day 199](https://github.com/vaskoz/dailycodingproblem-go/issues/409)
* [Day 200](https://github.com/vaskoz/dailycodingproblem-go/issues/411)
* [Day 201](https://github.com/vaskoz/dailycodingproblem-go/issues/415)
* [Day 202](https://github.com/vaskoz/dailycodingproblem-go/issues/417)
38 changes: 38 additions & 0 deletions day202/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package day202

// IsIntegerPalindrome returns true if the integer is a
// palindrome.
// Runs in O(digits) time and O(digits) space.
func IsIntegerPalindrome(i int) bool {
var digits []int
for i != 0 {
digits = append(digits, i%10)
i /= 10
}
for i := 0; i < len(digits)/2; i++ {
if digits[i] != digits[len(digits)-1-i] {
return false
}
}
return true
}

// IsIntegerPalindromeFaster returns true if the integer is a
// palindrome.
// Runs in O(digits) time and O(1) space.
func IsIntegerPalindromeFaster(i int) bool {
divisor := 1
for temp := i; temp/divisor > 10; divisor = divisor * 10 {
}
for i >= 10 {
highest := i / divisor
lowest := i % 10
if highest != lowest {
return false
}
i %= divisor
i /= 10
divisor /= 100
}
return true
}
49 changes: 49 additions & 0 deletions day202/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package day202

import "testing"

var testcases = []struct {
num int
expected bool
}{
{888, true},
{121, true},
{678, false},
{123124234323, false},
{123454321, true},
{23455432, true},
}

func TestIsIntegerPalindrome(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := IsIntegerPalindrome(tc.num); result != tc.expected {
t.Errorf("For input %v, expected %v, got %v", tc.num, tc.expected, result)
}
}
}

func BenchmarkIsIntegerPalindrome(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
IsIntegerPalindrome(tc.num)
}
}
}

func TestIsIntegerPalindromeFaster(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := IsIntegerPalindromeFaster(tc.num); result != tc.expected {
t.Errorf("For input %v, expected %v, got %v", tc.num, tc.expected, result)
}
}
}

func BenchmarkIsIntegerPalindromeFaster(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
IsIntegerPalindromeFaster(tc.num)
}
}
}

0 comments on commit fadea94

Please sign in to comment.