From 38ec5384fa3138a3b8f91109280ac90e18c2395a Mon Sep 17 00:00:00 2001 From: VicRen Date: Sat, 3 Oct 2020 22:25:38 +0800 Subject: [PATCH] largest palindrome product --- largest_palindrome_product/main.go | 34 +++++++++++++ largest_palindrome_product/palindrome_test.go | 48 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 largest_palindrome_product/main.go create mode 100644 largest_palindrome_product/palindrome_test.go diff --git a/largest_palindrome_product/main.go b/largest_palindrome_product/main.go new file mode 100644 index 0000000..2491f3d --- /dev/null +++ b/largest_palindrome_product/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "strconv" + "strings" +) + +func main() { + var n int + var x int + var y int + for i := 100; i < 1000; i++ { + for j := 100; j < 1000; j++ { + tmp := i * j + if tmp > n && IsPalindrome(tmp) { + x = i + y = j + n = tmp + } + } + } + fmt.Println(x, y, n) +} + +func IsPalindrome(n int) bool { + str := strconv.Itoa(n) + pb := strings.Builder{} + for i := len(str); i > 0; i-- { + pb.WriteString(str[i-1 : i]) + } + pstr := pb.String() + return str == pstr +} diff --git a/largest_palindrome_product/palindrome_test.go b/largest_palindrome_product/palindrome_test.go new file mode 100644 index 0000000..e276089 --- /dev/null +++ b/largest_palindrome_product/palindrome_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "testing" +) + +func TestIsPalindrome(t *testing.T) { + tt := []struct { + name string + input int + want bool + }{ + { + "1", + 1, + true, + }, + { + "11", + 11, + true, + }, + { + "1001", + 1001, + true, + }, + { + "123456654321", + 123456654321, + true, + }, + { + "123456754321", + 123456754321, + false, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + got := IsPalindrome(tc.input) + if got != tc.want { + t.Errorf("IsPalindrome(%d)=%v, want %v", tc.input, got, tc.want) + } + }) + } +}