一、原题
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