美文网首页Java 杂谈算法记录
从字符串中提取一个整形

从字符串中提取一个整形

作者: 要拿出真本事了 | 来源:发表于2019-07-02 12:58 被阅读0次

    要求描述

    从一个字符串中提取一个整数,要求如下:

    • 忽略字符串两边的空白
    • 从第一位开始读,只能为0-9 or -/+
    • 当提取的数值大于最值则取最值
    • 否则返回0

    可能出现的情况:
    " -42"、"+-32"、" 00000000000012345678"、" "、" 0000000000"、"-a32"。。。

    实现思路:

    • 调用String的类方法trim()去掉whitespace
    • 判断第一位是否为-/+,且下一位为数字
    • 忽略无效的0
    • 计算结果并判断其值是否超过int的最值

    实现代码

    public int myAtoi(String str) {
            if(str == null||str.trim().isEmpty())return 0;
            char trim[] = str.trim().toCharArray();//trim the string left and right whitespace
            int len = trim.length;
    
            boolean positive = true;//true stands for positive,false stands for negative
            long result = 0;
            int start = 0;
    
            // -/+ is available in first sign
            if (trim[start]=='-' || trim[start]=='+'){
                if (len>=2 && (trim[start+1] >= '0'&&trim[start+1] <= '9')){
                    if (trim[start]=='-')positive = false;
                    start++;
                }
            }
    
            for (; start < len; start++) {
                if (trim[start]<'0' || trim[start]>'9') break;
                if (result==0 && trim[start]=='0')continue;
                if (!(result == 0))result *= 10;
                int digit = trim[start]-48;
                result += digit;
                if(result > Integer.MAX_VALUE){
                    result = positive?Integer.MAX_VALUE:Integer.MIN_VALUE;
                    break;
                }
            }
            
            if(!positive) result = -result;
            
            return (int)result;
        }
    

    基础记录

    • Integer.MAX_VALUE = 0x80000000
      Integer.MIN_VALUE = 0x7fffffff
      Integer.MIN_VALUE - 1 = Integer.MAX_VALUE
      所以只需要判断结果是否比Integer.MAX_VALUE大
    • 0-9对应的char直接获取需要 - 48
    • 可以通过string的类方法substring来获取子字符串,再通过Integer.valueOf来得到结果,但是这样运行速度不如获取到char数组再做乘法和加法

    运行结果

    后记

    不代表正确答案,算法应该是个思想,不同的人写出来的结果会有所不同,如果有幸有人看到欢迎前来交流或者提出宝贵的意见!

    附上原题目

    The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

    The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

    If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

    If no valid conversion could be performed, a zero value is returned.

    相关文章

      网友评论

        本文标题:从字符串中提取一个整形

        本文链接:https://www.haomeiwen.com/subject/nakgcctx.html