golang实战------翻转字符串和整数

最近研究了下golang翻转字符串和整数的实现,感觉还挺有意思的。

代码如下所示:

package main

import (
	"fmt"
)

func main() {
	var str1 = "hello"
	str2 := "world"

	//str3 := str1 + " " + str2
	str3 := fmt.Sprintf("%s %s", str1, str2)
	fmt.Println(str3)

	reverseStr := revreseString(str3)
	fmt.Println(reverseStr)

	reverseStr = reverseString1(str3)
	fmt.Println(reverseStr)

	reverseStr = ReverseString(str3)
	fmt.Println(reverseStr)

	intA := 100
	fmt.Printf("origin int num=%d, reversed num=%d\n", intA, ReverseInt(intA))

	intA = 123
	fmt.Printf("origin int num=%d, reversed num=%d\n", intA, ReverseInt(intA))
}

// 反转字符串
func revreseString(str string) string {
	var result string
	strLen := len(str)
	for i := 0; i < strLen; i++ {
		result = result + fmt.Sprintf("%c", str[strLen-i-1])
	}
	return result
}

// 反转字符串
func reverseString1(str string) string {
	tmp := []byte(str)
	length := len(str)
	var result []byte
	for i := 0; i < length; i++ {
		result = append(result, tmp[length-i-1])
	}

	return string(result)
}

// 反转字符串(推荐用这种)
func ReverseString(s string) string {
	r := []rune(s)
	length := len(r)
	for i, j := 0, length-1; i < length/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

// 反转整数
func ReverseInt(x int) int {
	//题目要求其数值范围是 [−2^31,  2^31 − 1]。如果反转后的整数溢出,则返回 0。
	MaxInt32 := 1<<31 - 1
	MinInt32 := -1 << 31

	var num, newNum int
	for x != 0 { //直到x等于0,跳出循环
		a := x % 10
		newNum = num*10 + a

		num = newNum
		x = x / 10

		if num > MaxInt32 || num < MinInt32 {
			return 0
		}
	}

	return num
}

运行效果如下所示:

golang实战------翻转字符串和整数_第1张图片

你可能感兴趣的:(go)