LeetCode之回文数
一、题目描述
给你一个二维整数数组 matrix
, 返回 matrix
的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例2:
输入:matrix = [[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
二、解题思路
2.1 转字符串从两头比较
func isPalindrome(x int) bool {
// 去掉临界值
if x < 0 || (x % 10 == 0 && x != 0) {
return false
}
// 转成字符串之后两头开始相互比较
temp := strconv.Itoa(x)
length := len(temp) - 1
for i := 0; i <= length; i++ {
if temp[i] != temp[length - i] {
return false
}
}
return true
}
2.2 转换数字
func isPalindrome(x int) bool {
// 去掉临界值
if x < 0 || (x % 10 == 0 && x != 0) {
return false
}
// 将数字转换
newTemp := 0
for x > newTemp {
newTemp = newTemp * 10 + x % 10
x /= 10
}
return x == newTemp || x == newTemp / 10
}
2.3 比较
最后执行时间第一种用时是第二种的一半,内存消耗相同。
三、链接
题目链接:https://leetcode-cn.com/problems/palindrome-number/