241. 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).
样例
给出 "123", 返回 123.
public class Solution {
/**
* @param str: A string
* @return: An integer
*/
public int stringToInteger(String str) {
// write your code here
return Integer.parseInt(str);
//return Integer.valueOf(str);
}
}
public class Solution {
/**
* @param str: A string
* @return: An integer
*/
public int stringToInteger(String str) {
// write your code here
int integer = 0;
int negative = 0;//1为true是负数,0为false是正数
if (str.charAt(0) == '-'){
negative = 1;
}
for (int i = negative; i < str.length(); i++){
integer = integer * 10 + str.charAt(i)-'0';
//假设str=1000
//i=0 integer=0*10+1=1;
//i=1 integer=1*10+0=10;
//i=2 integer=10*10+0=100;
//i=3 integer=100*10+0=1000;
}
if (negative == 1){
integer = -integer;
}
return integer;
}
}

浙公网安备 33010602011771号