First, the subject description:
Atoi you to implement a function, it can convert a string to an integer.
First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far.
When we find the first non-space character is a positive or negative number, the combination of the symbols as much as possible with consecutive numbers up later, as the sign of integer; if the first non-space character is figures, which directly after the continuous numeric characters are combined to form an integer.
In addition to the string after a valid integer part may also exist extra characters, these characters can be ignored, they should not affect a function.
Note: if the character string in the first non-space character is not a valid integer character string is empty or contains only white space character string, then you will not need to be a function of conversion.
In any case, if the function can not effectively convert, 0 is returned.
Description:
We assume that the size of the environment can store 32-bit signed integer, then the value range of [-231 231--1]. If the value exceeds this range, return INT_MAX (231 - 1) or INT_MIN (-231).
Example 1:
输入: "42"
输出: 42
Example 2:
输入: " -42"
输出: -42
解释: 第一个非空白字符为 '-', 它是一个负号。
我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。
Example 3:
输入: "4193 with words"
输出: 4193
解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。
Example 4:
输入: "words and 987"
输出: 0
解释: 第一个非空字符是 'w', 但它不是数字或正、负号。
因此无法执行有效的转换。
Example 5:
输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。
因此返回 INT_MIN (−231) 。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/string-to-integer-atoi
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Second, the code Description:
class Solution {
public int myAtoi(String str) {
if(str.length()==0){
return 0;
}
//去除字符串两端的空格
str=str.trim( );
char[] ch=str.toCharArray();
//sign标记符号位
int sign=1;
//注意这里不能写成String s=" "
//第一位是正负号,第二位就是空格,不是数字, 就不用继续查找了。
String s="0";
for(int i=0;i<ch.length;i++){
if(i==0&&ch[i]=='-'){
sign*=-1;
}
else if(i==0&&ch[i]=='+'){
sign*=1;
}
else {
if(isLetter(ch[i])){
s+=ch[i];
}
else{
break;
}
}
}
try{
//将字符串通过parse()方法转化成基本数据类型
int num=Integer.parseInt(s)*sign;
return num;
}catch(Exception e){
//有超过 32 位有符号整数范围,根据符号位返回对应的值
if(sign>0){
return Integer.MAX_VALUE;
}
else{
return Integer.MIN_VALUE;
}
}
}
private boolean isLetter(char letter){
if(letter>='0'&&letter<='9'){
return true;
}
return false;
}
}