LeetCode8-StringtoInteger

【题目】

Implement atoi to convert a string to an integer.

用自己的方法实现将字符串转换成整型数字

【思路】

1、转换过程中有两个状态,start_flag=0表示转换未开始,start_flag=1表示转换已开始;

2、start_flag=0时,若出现‘-’,‘+’,‘数字’,则start_flag设为1,转换开始;若出现空格,则结束本次循环,继续查询;若出现其他字符,则返回0;

3、start_flag=1时,若出现数字,则更新结果,若出现其他字符则终止转换,返回当前结果;其中,要判断是否当前数值的加入是否会超出范围;

【Java代码】

public class Solution_8_string_to_integer {
	public int myAtoi(String str){
		int result = 0;
		int start_flag = 0;
		int negiv_flag = 0;
		for(int i = 0 ; i < str.length() ; i++){
			if(start_flag == 0 && (str.charAt(i)=='-' || str.charAt(i)=='+' || (str.charAt(i)>='0' && str.charAt(i)<='9'))){
				start_flag = 1;
				if(str.charAt(i) == '-'){
					negiv_flag = 1;
					continue;
				}
				else if(str.charAt(i) == '+'){
					negiv_flag = 0;
					continue;
				}
			}
			if(start_flag == 1){
				if(!(str.charAt(i)>='0' && str.charAt(i)<='9'))
					return negiv_flag == 1?-result:result;
				else{
					if(negiv_flag == 1 && (result > 214748364 || (result == 214748364 && str.charAt(i)-'0' > 8)))
						return -2147483648;
					if(negiv_flag == 0 && (result > 214748364 || (result == 214748364 && str.charAt(i)-'0' > 7)))
						return 2147483647;
					result = result*10 + str.charAt(i)-'0';
				}
			}else{
				if(str.charAt(i) != ' ')
					return 0;
				else
					continue;
			}
		}
		return negiv_flag == 1?-result:result;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值