Leetcode007--将字符串转换成整形


一、原题



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. 



二、中文



输入一个字符串类型的数据,将其转换成整形的数据并输出,其中需要考虑各种情况



三、举例



如输入-0099,我们输出的整形数字就是-99



四、思路



题目的思路其实比较简单,难的是要考虑各种字符串的输入情况,特别是要考虑到开头是空格和正负号的情况



五、程序




package LeetCode;

public class Leetcode008 {
	public static void main(String args[]){
		System.out.println(strToInteger("  -00999"));
	}
	   

	/**
	 * @param 将字符串转换成整形
	 * @return 转换完的整形数
	 */
	public static int strToInteger(String str){
		if(str == null || str.length() < 0){
			return -1;
		}
		
		//判断是正负和数字本身
		boolean positive = true;	
		int num = 0;
		int flag = 0;
		
		//当开头的时候是空格的是时候首先要消除空格
		while(str.charAt(flag) == ' '){
			flag++;
		}
		
		//用来判断是正是负
		if(str.charAt(flag) == '+'){
			positive = true;
			flag++;
		}else if(str.charAt(flag) == '-'){
			positive = false;
			flag++;
		}
		
		for(int i = flag; i < str.length(); i++){
			num = num * 10 + str.charAt(i) - '0';
		}
		
		// 判断正负并将其进行返回
		if(positive == true){
			return num;
		}else if(positive == false){
			return num * (-1);
		}
		return 0;	
	}
}

-----------------------output--------------------------

-999


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值