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);
        }
    }
  • 相关阅读:
    C基础之移位操作
    实现itoa()
    Python的time模块的clock方法在不同平台的效果不同
    __stdcall与__cdecl之区别浅析及相关知识
    Python 字典 dictionary changed size during iteration
    Windows下printf输出long long类型
    inotify也会爆棚
    一条对“失控的腾讯帝国:企鹅无法把控手机市场”的评论
    imfunny程序员的增量发展
    程序员第一定律:关于技能和收入
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4261923.html
Copyright © 2011-2022 走看看