[Golang] Check if Integer is Palindromic Number


Check if an decimal integer number (int64) is palindrome in Golang.

The algorithm:

  1. Get absolute value of the integer (int64).
  2. Convert the int64 type to string type using strconv.FormatInt.
  3. Check if string[0] == string[n-1] where n is the length of the string, then check if string[1] == string[n-2] ... and so on, until the middle digit of string. If all are true, return true. Otherwise return false.

Run Code on Go Playground

decimal.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package palindrome

import (
	"strconv"
)

func IsDecimalPalindromeNumber(n int64) bool {
	if n < 0 {
		n = -n
	}

	s := strconv.FormatInt(n, 10)
	bound := (len(s) / 2) + 1
	for i := 0; i < bound; i++ {
		if s[i] != s[len(s)-1-i] {
			return false
		}
	}
	return true
}

Testing:

decimal_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package palindrome

import (
	"testing"
)

func TestIsDecimalPalindromeNumber(t *testing.T) {
	if IsDecimalPalindromeNumber(123) != false {
		t.Error(123)
		return
	}
	if IsDecimalPalindromeNumber(1221) != true {
		t.Error(1221)
		return
	}
	if IsDecimalPalindromeNumber(-125521) != true {
		t.Error(-125521)
		return
	}
	if IsDecimalPalindromeNumber(-12521) != true {
		t.Error(-12521)
		return
	}
	if IsDecimalPalindromeNumber(12521) != true {
		t.Error(12521)
		return
	}
	if IsDecimalPalindromeNumber(-1251) != false {
		t.Error(-1251)
		return
	}
	if IsDecimalPalindromeNumber(1251) != false {
		t.Error(1251)
		return
	}
}

Tested on:

  • Ubuntu Linux 16.10, Go 1.8.1
  • Go Playground

References:

[1]
[2][Golang] Type Conversion between String and Integer
[3]
[4]
[5]
[6]