zoukankan      html  css  js  c++  java
  • String to Integer (atoi)

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    这道题要考虑的细节还蛮多的,str若能convert必须满足以下几点要求:(1)str非空且包含数字;(2)str第一个非空字符必须是+ or - or 数字;(3)若第一个非空字符为+ or -,则紧跟着必须为数字;(4)若转换后的值超过int的最大最小值,则返回MAX_VALUE或者MIN_VALUE。

    import java.util.regex.*;
    public class Solution {
        public int atoi(String str) {
            
            //排除空串或者str不含数字的情况
            if(str.length() == 0||str.replaceAll("\D","").length() == 0){
                return 0;
            }
            
            //排除第一个非空字符不是+-或者数字的情况
            String temp = str.replace(" ","");
            if(temp.charAt(0)!='+'&&temp.charAt(0)!='-'&&(temp.charAt(0)>'9'||temp.charAt(0)<'0')){
                return 0;
            }
            
            //排除+-后面一个字符不是数字的情况
            int index;
            if(temp.charAt(0) == '-'){
                index = str.indexOf('-');
                if(str.charAt(index+1)>'9'||str.charAt(index+1)<'0'){
                    return 0;
                }
            }
            
            if(temp.charAt(0) == '+'){
                index = str.indexOf('+');
                if(str.charAt(index+1)>'9'||str.charAt(index+1)<'0'){
                    return 0;
                }
            }
            
            //排除所有特殊情况后用正则表达式匹配
            String re = "";
            Pattern p = Pattern.compile("[+-]?\d+");
            Matcher m = p.matcher(str);
            if(m.find()){
                re = m.group();
            }
            else{
                return 0;
            }
            //若所得数字大于MAX_VALUE则返回MAX_VALUE
            if(Double.valueOf(re)>Integer.MAX_VALUE){
                return Integer.MAX_VALUE;
            }
            //若所得数字小于MIN_VALUE则返回MIN_VALUE
            if(Double.valueOf(re)<Integer.MIN_VALUE){
                return Integer.MIN_VALUE;
            }
            
            return Integer.valueOf(re);
        }
    }
  • 相关阅读:
    PC版优酷的一次异常
    颜宁开讲啦谈理性思考
    李彦宏开讲啦谈判断能力
    尝试插入cctv视频
    selenium中quit与close方法的区别
    CodeForces 131C The World is a Theatre(组合数)
    CodeForces 446A DZY Loves Sequences(dp)
    UVA 1631 Locker(密码锁)(dp记忆化搜索)
    UVA 1630 Folding(串折叠)(dp记忆化搜索)
    UVA 1629 Cake slicing(切蛋糕)(dp记忆化搜索)
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4261923.html
Copyright © 2011-2022 走看看