zoukankan      html  css  js  c++  java
  • [算法]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.

    Analysis

    The following cases should be considered for this problem:

    1. null or empty string
    2. white spaces
    3. +/- sign
    4. calculate real value
    5. handle min & max
    

    Java Solution

    public int atoi(String str) {
    
    	if (str == null || str.length() < 1)
    
    		return 0;
    
    	// trim white spaces
    
    	str = str.trim(); 
    
    	char flag = '+'; 
    
    	// check negative or positive
    
    	int i = 0;
    
    	if (str.charAt(0) == '-') {
    
    		flag = '-';
    
    		i++;
    
    	} else if (str.charAt(0) == '+') {
    
    		i++;
    
    	}
    
    	// use double to store result
    
    	double result = 0;
    
    	// calculate value
    
    	while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
    
    		result = result * 10 + (str.charAt(i) - '0');
    
    		i++;
    
    	} 
    
    	if (flag == '-')
    
    		result = -result;
    
    	// handle max and min
    
    	if (result > Integer.MAX_VALUE)
    
    		return Integer.MAX_VALUE;
    
    	if (result < Integer.MIN_VALUE)
    
    		return Integer.MIN_VALUE;
    
    	return (int) result;
    
    }
  • 相关阅读:
    php内核为变量的值分配内存的几个宏
    php7 引用成为一种类型
    function参数
    execvp php-fpm reload使用的函数
    fastcgi
    php-fpm定时器
    php 类继承
    php 对象 调用静态方法
    php unset变量
    php5数组与php7数组区别
  • 原文地址:https://www.cnblogs.com/xiaomoxian/p/5194118.html
Copyright © 2011-2022 走看看