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);
        }
    }
  • 相关阅读:
    异步底层代码实现邮件发送
    MongoDB+Echarts+DWebSocket
    celery定时任务+redis有序集合实现实时访问人数
    位运算+数据库两种方式实现中间件权限操作
    cocoapod 引入url
    pdf转xml
    Flutter项目安卓下载地址
    ios Mac 利用SVN进行cocoapod私有库的使用
    KVO
    类别和类扩展的区别
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4261923.html
Copyright © 2011-2022 走看看