[Toggle Comments]
package main // file: impl-001.go import ( "strconv" ) // Stringify the number and compare. // // time: O(log(N)); where N is the input number. // (For number x, log(x) will be the number of digits it has.) // // space: O(log(N)) // (We store ~log(N) characters in variable `v`.) func isPalindromeStr(x int) bool { v := strconv.Itoa(x) l := len(v) for i, _ := range v { // For i == 4; l/2 is 2 xx(x)x // For i == 5; l/2 is 2 xx(x)xx // For i == 3; l/2 is 1 x(x)x // // When `i` is at `l/2`, we have already checked half of the number. // And all the digits so far mirror each other. // Therefore, if i reaches l/2, we can conclude that the number is // a palindrome. if i == l/2 { return true } // Check mirroring digits. Even a single mismatch means our number is // not a palindrome. currentIndex := i mirrorIndex := l - i - 1 if v[currentIndex] != v[mirrorIndex] { return false } } // We should not reach here, but “just in case”. return true } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */