zoukankan      html  css  js  c++  java
  • 【LeetCode】8. 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.

    Requirements for atoi:

      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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

    思路:

      该题目是说将string类型的字符串转换成整型数据,类似于C++库里的atoi函数,解决该题目的关键在于两个方面:
      (1)字符串格式的合法判断
      (2)转换结果的溢出判断
    public class Solution {
        public int myAtoi(String str) {
            str=str.trim();
            char[] arr=str.toCharArray();
            if(arr.length==0){
                return 0;
            }
            
            int i=0;
            boolean symbol=true;
            if(arr[i]=='-'){
                symbol=false;
                i++;
            }else if(arr[i]=='+'){
                i++;
            }
        
            
            long MAX_VALUE=Integer.MAX_VALUE;
            long MIN_VALUE=Integer.MIN_VALUE;
            long num=0;
            for(int j=i;j<arr.length;j++){
                if(arr[j]>='0'&&arr[j]<='9'){
                    num=num*10+arr[j]-'0';
                }else{
                    break;
                }
                
                if(!symbol&&(0-num<MIN_VALUE)){
                    return Integer.MIN_VALUE;
                }else if(symbol&&(num>MAX_VALUE)){
                    return Integer.MAX_VALUE;
                }
            }
            
            return symbol?new Long(num).intValue():new Long(0-num).intValue();
        }
    }
  • 相关阅读:
    P3919 【模板】可持久化线段树 1(可持久化数组)
    P3384 【模板】轻重链剖分
    P2680_运输计划
    CSP-S2 T4/P7078 贪吃蛇_set 70pts/100pts(O2)
    SPFA判负环
    P6394 樱花,还有你
    CSP-S2T4/P7078 贪吃蛇
    【模板】单源最短路径(标准版)
    U135649 皇室战争
    【离散数学】实验三 偏序关系中盖住关系的求取及格论中有补格的判定
  • 原文地址:https://www.cnblogs.com/zhstudy/p/6001442.html
Copyright © 2011-2022 走看看