String to Integer
题目:
Given a string, convert it to an integer. You may assume the string is a valid integer number that can be presented by a signed 32bit integer (-231 ~ 231-1).
分析:
不管怎么说还是比atoi II好做不少
解法
public class Solution {
/**
* @param str a string
* @return an integer
*/
public int stringToInteger(String str) {
// Write your code here
if (str.length() == 0) {
return 0;
}
boolean flag = true;
int start = 0;
if (str.charAt(0) == '-') {
flag = false;
start++;
}
int res = 0;
for (int i = start; i < str.length(); i++) {
int temp = str.charAt(i) - '0';
res = res * 10 + temp;
}
if (flag == false) {
res = -res;
}
return res;
}
}