zoukankan      html  css  js  c++  java
  • leecode---08---基本数据类型转换---str到整形

     
     
    题意
    把一个字符串转化成整数
     
     
    分析
    主要就是边界条件的判断问题
    1.先把空格去掉,str = str.trim();
    2.第一个字符可能是符号或者不是符号。对第一个字符进行特殊判断。
    3.用一个临时的double存数字,遍历str的每一个字符从左往右。
    4.最后进行符号的判定
    5.越界判定
     
    代码
    class Solution {
        public int myAtoi(String str) {
            if (str == null || str.length() == 0) return 0;
            
            double result = 0;//用来保存最终结果
            char flag = '+';//用来保存正负号
            int index = 0;//使用index指向下标来进行移动
            
            str = str.trim();//去除掉空格和首位的正负号
            if (str.charAt(0) == '-') {
                flag = '-';
                index++;
            } else if (str.charAt(0) == '+') {
                index++;
            }
            
            //然后开始从第二个数字进行判断了,如果出现非字符直接中断
            for (; index < str.length(); index++) {
                char c = str.charAt(index);
                if (c >= '0' || c <= '9') {//正常数字从前往后插入
                    result = result * 10 + (c - '0');
                    index++;
                } else {
                    return 0;
                }
            }
            
            //最后因为结果存在了result里面,需要进行正负号的判断和越界的判断
            if (flag = '-') result = -result;
            if (result > INTEGER.MAX_VALUE) return INTEGER.MAX_VALUE;
            if (result < INTEGER.MIN_VALUE) return INTEGER.MIN_VALUE;
            return result;
        }
    }
     
     
  • 相关阅读:
    Codeforces 1045C Hyperspace Highways (看题解) 圆方树
    Codeforces 316E3 线段树 + 斐波那切数列 (看题解)
    Codeforces 803G Periodic RMQ Problem 线段树
    Codeforces 420D Cup Trick 平衡树
    Codeforces 295E Yaroslav and Points 线段树
    Codeforces 196E Opening Portals MST (看题解)
    Codeforces 653F Paper task SA
    Codeforces 542A Place Your Ad Here
    python基础 异常与返回
    mongodb 删除
  • 原文地址:https://www.cnblogs.com/buptyuhanwen/p/8906008.html
Copyright © 2011-2022 走看看