zoukankan      html  css  js  c++  java
  • Palindrome Number && Reverse Number

    Problem I: 判断数字是不是回文字符串形式

    Determine whether an integer is a palindrome. Do this without extra space.

    click to show spoilers.

    Some hints:

    Could negative integers be palindromes? (ie, -1)

    If you are thinking of converting the integer to string, note the restriction of using extra space.

    You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

    There is a more generic way of solving this problem.

    解决思路

    难点在于不使用辅助空间,也就是说不能转成字符串形式再进行判断。

    数字操作也就是%和/两种,整体方法如下:

    (1)得到最大单位div,如输入的数为1001,则div为1000;

    (2)取余和取被除数,然后进行判断,是否相等;

    (3)得到去除两边数字的数字,div=div/100,再进入(2),直到输入的数为0为止。

    程序

    public class Solution {
        public boolean isPalindrome(int x) {
            if (x < 0) {
                return false;
            }
            
            int div = 1;
            while (x / div >= 10) {
                div *= 10;
            }
            
            while (x > 0) {
                int right = x % 10;
                int left = x / div;
                if (left != right) {
                    return false;
                }
                x = (x % div) / 10;
                div /= 100;
            }
            
            return true;
        }
    }
    

    Problem II: 翻转数字

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    click to show spoilers.

    Have you thought about this?

    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    解决思路

    善用%和/两种符号。

    需要注意的是对于越界情况的处理。

    程序

    public class Solution {
        public int reverse(int x) {
            long sum = 0;
            while (x != 0) {
                sum *= 10;
                sum += x % 10;
                x /= 10;
            }
            if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
                return 0;
            }
            return (int)sum;
        }
    }
    
  • 相关阅读:
    Python IDE
    Codeforces Beta Round #69 Div1
    HDU1595 find the longest of the shortest[最短路]
    MFC/OpenGL下的调色板
    ApacheCN 编程/大数据/数据科学/人工智能学习资源 2019.12
    计算机电子书 2016 BiliDrive 备份
    计算机电子书 2017 BiliDrive 备份
    Java项目中常见的异常处理
    从小工到专家第三次读后感
    《梦断代码》读后感1
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4734048.html
Copyright © 2011-2022 走看看