zoukankan      html  css  js  c++  java
  • leetcode--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.

    spoilers alert... click to show requirements for atoi.

    public class Solution {
        public int atoi(String str) {
            String trimStr = str.trim();
    		int len = trimStr.length();
    		if(len == 0) return 0;
    		long result = 0;
    		boolean negative = false;
    		int start = 0;
    		if(trimStr.charAt(0) == '-' || trimStr.charAt(0) == '+'){
    			negative = (trimStr.charAt(0) == '-');
    			++start;
    		}
    		while (start < len){
    			if(trimStr.charAt(start) >= '0' && trimStr.charAt(start) <='9'){
    				result = (result * 10) + (trimStr.charAt(start) - '0');
    				
    				//compare with the max integer and min integer
    				if(negative && result >= (long)Integer.MAX_VALUE + 1) //do not forget the conversion
    				    return Integer.MIN_VALUE;
    				if(!negative  && result >= Integer.MAX_VALUE)
    					return Integer.MAX_VALUE;
    			}
    			else //a character not a digit
    				break;
    			++start;
    		}
    		if(negative)
    		    result *= (-1);
    		return (int) result;
        }
    }
    

      

      

  • 相关阅读:
    vijos 1426
    2455 繁忙的都市
    2104 删除物品
    3235 战争
    BZOJ 2962
    COGS 265 线段覆盖
    P2184 贪婪大陆
    0729模拟赛解题报告
    BZOJ 1012
    BZOJ 2763
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3561566.html
Copyright © 2011-2022 走看看