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).
Example
Given "123", return 123.
public class Solution {
/**
* @param str a string
* @return an integer
*/
public int stringToInteger(String str) {
// Write your code here
boolean neg = false;
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '-') {
neg = true;
continue;
}
else
result = result * 10 + (str.charAt(i) - '0');
}
if (neg)
return -result;
else
return result;
}
}