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;
        }
    }
    
  • 相关阅读:
    Win10 WSL Ubuntu18.04 编译安装MySQL5.7
    PHP7 深入理解
    php session 测试
    nginx 匹配路由分发php和golang
    composer 库无法提交git
    Win10 1803安装Ubuntu1804子系统
    dhtmlxTreeGrid使用
    win7 64位系统下安装PL/SQL连接Oracle服务器的解决方法
    转载--eclipse快捷键
    JUnit4学习笔记2-Eclipse中使用JUint4进行单元测试
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4734048.html
Copyright © 2011-2022 走看看