反向整数组

如何更改1234554321?对于字符串,您可以将字符串更改为 a rune,然后将其反转,但不能对整数执行相同操作。我已经搜索过,发现没有人谈论这个。例子
131415>>> 514131
1357>>> 7531
123a>>> ERROR
-EDIT-
我在想,为什么不创建一个slice和索引呢?
然后我意识到你不能索引int
http://play.golang.org/p/SUSg04tZsc )
我的新问题是
你如何索引一个 int? 或者
你如何反转一个int?

万千封印
浏览 168回答 3
3回答

尚方宝剑之说

这是一个不使用索引的解决方案 intpackage mainimport (    "fmt")func reverse_int(n int) int {    new_int := 0    for n > 0 {        remainder := n % 10        new_int *= 10        new_int += remainder         n /= 10    }    return new_int }func main() {    fmt.Println(reverse_int(123456))    fmt.Println(reverse_int(100))    fmt.Println(reverse_int(1001))    fmt.Println(reverse_int(131415))    fmt.Println(reverse_int(1357))}结果:654321110015141317531

慕的地6264312

与第一个答案非常相似,但这会检查以确保您不会超出类型范围。func reverse(x int) int {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; rev := 0&nbsp; &nbsp; for x != 0 {&nbsp; &nbsp; &nbsp; &nbsp; pop := x % 10&nbsp; &nbsp; &nbsp; &nbsp; x /=&nbsp; 10&nbsp; &nbsp; &nbsp; &nbsp; if rev > math.MaxInt32/10 || (rev == math.MaxInt32 /10 && pop > 7) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if rev < math.MinInt32/10 || (rev == math.MinInt32/10 && pop < -8) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; rev = rev * 10 + pop&nbsp; &nbsp; }&nbsp; &nbsp; return rev}

胡说叔叔

我将整数转换为字符串,反转字符串,然后将结果转换回字符串。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strconv")func main() {&nbsp; &nbsp; fmt.Println(reverse_int(123456))&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(reverse_int(100))&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(reverse_int(1001))&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(reverse_int(131415))&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(reverse_int(1357))}func reverse_int(value int) int {&nbsp; &nbsp; intString := strconv.Itoa(value)&nbsp; &nbsp; newString := ""&nbsp; &nbsp; for x := len(intString); x > 0; x-- {&nbsp; &nbsp; &nbsp; &nbsp; newString += string(intString[x - 1])&nbsp; &nbsp; }&nbsp; &nbsp; newInt, err := strconv.Atoi(newString)&nbsp; &nbsp; if(err != nil){&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Error converting string to int")&nbsp; &nbsp; }&nbsp; &nbsp; return newInt}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go