Skip to content

Commit

Permalink
day 202: faster version without extra space
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 12, 2019
1 parent 5502679 commit 37d6c0e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
20 changes: 20 additions & 0 deletions day202/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,23 @@ func IsIntegerPalindrome(i int) bool {
}
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
}
20 changes: 20 additions & 0 deletions day202/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ var testcases = []struct {
{888, true},
{121, true},
{678, false},
{123124234323, false},
{123454321, true},
{23455432, true},
}

func TestIsIntegerPalindrome(t *testing.T) {
Expand All @@ -27,3 +30,20 @@ func BenchmarkIsIntegerPalindrome(b *testing.B) {
}
}
}

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 37d6c0e

Please sign in to comment.