day9接口 练习7.10

master
独孤伶俜 2022-12-17 20:45:16 +08:00
parent 7ea088b7e3
commit e71b83ef5d
1 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package main
import (
"fmt"
"sort"
"strings"
)
func IsPalindrome(s sort.Interface) bool {
for i, j := 0, s.Len()-1; i < j; i, j = i+1, j-1 {
if s.Less(i, j) || s.Less(j, i) {
return false
}
}
return true
}
func StrToSlice(str string) []string {
return strings.Split(str, "")
}
func IntToSlice(num int) []int {
var s []int
for num > 0 {
s = append(s, num%10)
num /= 10
}
return s
}
func main() {
var str = "abcdcba"
// 将字符串转为[]string
s := StrToSlice(str)
fmt.Println(str, ":", IsPalindrome(sort.StringSlice(s))) // abcdcba : true
var num = 123321
// 将数字转为[]int
nums := IntToSlice(num)
fmt.Println(num, ":", IsPalindrome(sort.IntSlice(nums))) // 123321 : true
num = 123456
nums = IntToSlice(num)
fmt.Println(num, ":", IsPalindrome(sort.IntSlice(nums))) // 123456 : false
}