[LeetCode] 9. Palindrome Number

题:https://leetcode.com/problems/palindrome-number/description/

题目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

  1. Coud you solve it without converting the integer to a string?

题目大意

判断数字书 是否为回文。
要求不占用多的 空间。

思路

剔除特殊情况,如 0 ,负数,10的倍数。

很容易 将 数字 反向。

可以将 数字 进行方向操作 ,暂时结果为 right。当right 大于 去除低位的 原数x时,停止。

若right == x。数字为 偶个字符对称。
若right/10 == x。数字为 奇个字符对称。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int tres = 0;
    public void in_order_traversal(TreeNode root){
        if(root==null)
            return;
        in_order_traversal(root.right);
        tres += root.val;
        root.val = tres;
        in_order_traversal(root.left);
    }
    
    public TreeNode convertBST(TreeNode root) {
        in_order_traversal(root);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/84099719