[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.


思路:

实现字符串转换为int型整数并不难,只是有好多中输入情况需要考虑,容易造成遗漏。首先看一下c++ 中atoi的定义:

-----------------------------------

atoi

int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

The function first discards as many whitespace characters (as in isspace) 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 base-10 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 and zero is returned.


Return Value

On success, the function returns the converted integral number as an int value.
If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.

------------------------------------------

可以看出需要注意的有以下几点:

  1. 去掉前面的空格
  2. 注意开始时候的符号 + -
  3. 忽略数字后面的杂七杂八字符
  4. 考虑溢出的情况。

考虑了上面几方面,代码就可以AC了。


代码:

public class String_To_Integer { //java
	public static int atoi(String str) {
		int haveMinus = 1;
		long result = 0;  
		
		if(str == null || str.trim().isEmpty())
			return 0;
		
		//chech + - 
		str = str.trim();
		if(str.charAt(0) == '-'){
			str = str.substring(1);
			haveMinus = -1;
		}else if(str.charAt(0) == '+')
			str = str.substring(1);
		
		//check num
		for(int i = 0;i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'; i++){
			result = result*10 + (str.charAt(i)- '0');
		}
		
		//deal overflow
		if(result > 2147483647 && haveMinus == 1)
			return 2147483647;
		if(result > 2147483647 && haveMinus == -1)
			return -2147483648;
		
		return haveMinus*(int)result;
    }
	
	public static void main(String [] args){
		System.out.println(String_To_Integer.atoi("2147483648"));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值