LeetCode学习-golang是否是回文(题9)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/88393065

题面

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

源码

func IsPalindrome(x int) (result bool) {
	if x < 0 || (x%10==0 && x!=0){
		result = false
	}else {
		reverse:=0
		for x>reverse{
			reverse = reverse*10+x%10
			x = x/10
		}
		result = (x==reverse) || (x==reverse/10)
	}
	return
}

测试代码及结果

package question1_10

import (
	"fmt"
	"github.com/glw0223/LeetCode-go/question1_10"
	"testing"
)

func TestIsPalindrome(t *testing.T){
	result:=question1_10.IsPalindrome(121)
	fmt.Println(result)
	result=question1_10.IsPalindrome(-121)
	fmt.Println(result)
	result=question1_10.IsPalindrome(10)
	fmt.Println(result)
}
API server listening at: 127.0.0.1:56526
=== RUN   TestIsPalindrome
true
false
false
--- PASS: TestIsPalindrome (0.00s)
PASS

Debugger finished with exit code 0

复杂度

时间复杂度: O ( log 10 ( n ) ) O(\log_{10}(n)) 。每次迭代,输入除以10。
空间复杂度: O ( 1 ) O(1)

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/88393065
今日推荐