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;
        }
    }
    

      

      

  • 相关阅读:
    SANBA服务和FTP服务
    rpm和yum软件管理
    Linux进程管理
    Linux网络技术管理
    RAID磁盘阵列及CentOS7启动流程
    Linux磁盘管理及Lvm
    Linux计划任务及压缩归档
    Linux权限管理
    Linux用户及用户组管理
    vim 编辑器
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3561566.html
Copyright © 2011-2022 走看看