获取string中单一的值
String a="中国";
char b=a.charAt(0);
public static int myAtoi(String str) {
long result = 0;
int m = 0;//index of str
if(str.length() < 1){ //注意可以输入一个空的‘’两个引号之间啥都没 空格都没
return 0;
}
str = str.trim(); //整形整掉所有前面连贯的空格 如’ 10’
if (str.charAt(0) == '+' || str.charAt(0) == '-'){//处理符号以及第一个是空的话
m = m+1;
}
for(;m<str.length();m++){
if(str.charAt(m) < '0' || str.charAt(m) >'9'){ //atoi规定 数字后面的符号不影响数字 如" -0012a42" 转化为-12
return (int) result;
}
int item = 1;//用于处理负数
if (str.charAt(0) == '-'){ //注意负数
item = -1;
}
result = result*10 + item*(str.charAt(m) - '0');// 利用ascii的差值求数
if (result > Integer.MAX_VALUE)//溢出处理 规定 If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
return (int) result;
}
}
标准答案(其实思路一样 标准答案的structure整齐一点)
public int atoi(String str) {
if (str == null || str.length() < 1)
return 0;
// trim white spaces
str = str.trim();
char flag = '+';
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
String a="中国";
char b=a.charAt(0);
public static int myAtoi(String str) {
long result = 0;
int m = 0;//index of str
if(str.length() < 1){ //注意可以输入一个空的‘’两个引号之间啥都没 空格都没
return 0;
}
str = str.trim(); //整形整掉所有前面连贯的空格 如’ 10’
if (str.charAt(0) == '+' || str.charAt(0) == '-'){//处理符号以及第一个是空的话
m = m+1;
}
for(;m<str.length();m++){
if(str.charAt(m) < '0' || str.charAt(m) >'9'){ //atoi规定 数字后面的符号不影响数字 如" -0012a42" 转化为-12
return (int) result;
}
int item = 1;//用于处理负数
if (str.charAt(0) == '-'){ //注意负数
item = -1;
}
result = result*10 + item*(str.charAt(m) - '0');// 利用ascii的差值求数
if (result > Integer.MAX_VALUE)//溢出处理 规定 If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
return (int) result;
}
}
标准答案(其实思路一样 标准答案的structure整齐一点)
public int atoi(String str) {
if (str == null || str.length() < 1)
return 0;
// trim white spaces
str = str.trim();
char flag = '+';
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;