1. 程式人生 > >7. Reverse Integer Go語言

7. Reverse Integer Go語言

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321 Example 2:

Input: -123 Output: -321 Example 3:

Input: 120 Output: 21

思路: 1、將整數轉化成字元陣列; 2、對字元陣列進行反轉操作; 3、拼接字元陣列中的元素,進行返回即可

package main

import (
	"fmt"
	"strconv"
)

func main()  {
	intput := 123
	ret := reverse
(intput) fmt.Println(ret) } func reverse(x int) int { MIN_INT := -2147483648 MAX_INT := 2147483647 if (x < MIN_INT || x > MAX_INT){ return 0 } if ((x > -9) && (x < 9)){ return x } isNegative := false if (x <0){ x = (-1) * x isNegative = true } stringTem := strconv.
Itoa(x) stringArrs := []byte(stringTem) for beg, end := 0, len(stringArrs) - 1; beg < end; beg, end = beg + 1, end - 1{ tem := stringArrs[beg] stringArrs[beg] = stringArrs[end] stringArrs[end] = tem } retBeg := 0 for { if stringArrs[retBeg] == '0' { retBeg++ } else { break } }
stringRet := string(stringArrs[retBeg:]) if isNegative == true { stringRet = "-" +stringRet } temRet,_ := strconv.ParseInt(stringRet,10,64) if (temRet < int64(MIN_INT) || temRet > int64(MAX_INT)){ return 0 } return int(temRet) }