7. 整数反转

This commit is contained in:
li_chx 2026-03-29 21:58:42 +08:00
parent 64c805cf06
commit 51984f6f9b
Signed by: li_chx
GPG Key ID: C7CF27EFA1E58BAC
1 changed files with 77 additions and 41 deletions

118
main.go
View File

@ -1,55 +1,91 @@
package main package main
import "fmt" import (
"fmt"
"strconv"
"strings"
)
// ListNode Definition for singly-linked list. //type Test interface {
type ListNode struct { //}
Val int //
Next *ListNode //func condTest(cond *sync.Cond) {
} // cond.L.Lock()
// cond.Wait()
// fmt.Println("condTest")
// cond.L.Unlock()
//}
//func chanTest(ch chan<- *Test) {
//
//}
func isPalindrome(head *ListNode) bool { func reverse(x int) int {
srcHead := head neg := false
head = head.Next if x < 0 {
// var left, right *ListNode neg = true
cnt := 1 x = -x
for head != nil {
head = head.Next
cnt++
} }
head = srcHead.Next s := fmt.Sprintf("%d", x)
lastNode := srcHead var sb strings.Builder
srcHead.Next = nil for i := len(s) - 1; i >= 0; i-- {
half := cnt / 2 sb.WriteByte(s[i])
half--
for range half {
p := head.Next
head.Next = lastNode
lastNode = head
head = p
} }
if cnt&1 == 1 { s = sb.String()
head = head.Next var ans int32 = 0
for c := range s {
t, _ := strconv.ParseUint(string(s[c]), 10, 16)
ans = ans*10 + int32(t)
} }
for head != nil && lastNode != nil { if neg {
if head.Val != lastNode.Val { ans = -ans
return false x = -x
}
s1, s2 := fmt.Sprintf("%d", x), fmt.Sprintf("%d", ans)
if neg {
s1 = s1[1:]
s2 = s2[1:]
}
if len(s1) != len(s2) {
for len(s2) < len(s1) {
s2 = "0" + s2
} }
head = head.Next
lastNode = lastNode.Next
} }
if head != nil || lastNode != nil { for i := 0; i < len(s1); i++ {
return false if s1[i] != s2[len(s2)-1-i] {
return 0
}
} }
return true return int(ans)
} }
//9646324351
//2147483648
func main() { func main() {
isPalindrome := isPalindrome(&ListNode{ fmt.Println(reverse(1534236469))
Val: 1, //var x int = 16
Next: &ListNode{ //var y any = x
Val: 2, //if _, ok := y.(int); ok {
}, // fmt.Println(x)
}) //}
fmt.Printf("isPalindrome: %v\n", isPalindrome) //if _, ok := y.(int32); ok {
// fmt.Println(x)
//}
//var mu sync.Mutex
//sync.NewCond(&mu)
//make(chan *Test, 6)
//var wg sync.WaitGroup
//wg.Add(1)
//wg.Done()
//var mu sync.Mutex
//cond := sync.NewCond(&mu)
//
//go condTest(cond)
//go condTest(cond)
//
//time.Sleep(time.Second * 2)
//cond.L.Lock()
//cond.Broadcast()
//cond.L.Unlock()
//time.Sleep(time.Second * 2)
} }