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;
        }
    }
    
  • 相关阅读:
    asp.net[web.config] httphandlers 与实现自由定义访问地址
    Web.config配置文件详解
    ASP.NET十分有用的页面间传值方法(转)
    web.config中authorization下的location中的path的设置 (转)
    基于FormsAuthentication的用户、角色身份认证(转)
    FormsAuthentication.RedirectFromLoginPage 登录
    php代码审计-下载站系统Simple Down v5.5.1 xss跨站漏洞分析
    创建二维码生成器
    更新自制入库价格(结账)
    常用的系统存储过程
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4734048.html
Copyright © 2011-2022 走看看