479.largest-palindrome-product.go 743 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. func largestPalindrome(n int) int {
  2. // mod 1337
  3. if n == 1 {
  4. return 9
  5. }
  6. upper := int(math.Pow10(n)) - 1
  7. lower := upper / 10
  8. for i := upper; lower < i; i-- {
  9. pa := toPalindrome(i)
  10. bound := int(math.Sqrt(float64(pa)))
  11. for j := upper; j >= bound; j-- {
  12. if pa%j != 0 {
  13. continue
  14. }
  15. if ratio := pa / j; lower < ratio && ratio <= upper {
  16. return pa % 1337
  17. }
  18. }
  19. }
  20. return -1 // Not found
  21. }
  22. func toPalindrome(x int) (res int) {
  23. num := make([]int, 64)
  24. lo, hi := 0, 0
  25. for ; x != 0; x /= 10 {
  26. num[lo] = x % 10
  27. lo++
  28. }
  29. copy(num[lo:], num[:lo])
  30. for hi, lo = lo, lo-1; 0 <= lo; lo, hi = lo-1, hi+1 {
  31. num[lo] = num[hi]
  32. }
  33. for i, base := 0, 1; i < hi; i, base = i+1, base*10 {
  34. res += num[i] * base
  35. }
  36. return
  37. }