您的位置:首页 > 职场人生

剑指offer - 面试题49:把字符串转换为整数

2018-02-04 13:10 246 查看
package Chapter7;
/*
* input:
* "+343434"
* "-323232"
* "0"
* output:
* 343434
* 323232
* 0
*/
public class _49_str_to_num {
public static void main(String[] args) {
String str = "-000000000000000939";
System.out.println(new _49_function().str_to_num(str));
}
}

class _49_function {
final static int Max = 0x7fffffff;
final static int Min = 0x80000000;
int str_to_num(String str) {
// 1 空
if (str == null) return Min;
// 2 控制范围
// +2147483647
// -2147483648
char []ch = str.toCharArray();
int len = str.length();
// 位数
int num = ch.length;
for (int i = 1; i < len; i++) {
if (ch[i] == '0') num--;
else break;
}
if (num > 11) return ch[0] == '+' ? Max : Min;
// 3 转换
int res = 0;
int carry = 1;
for (int i = len - 1; i > 0; i--) {
int digit = ch[i] - '0';
// 保证数字
if (digit < 0 || digit > 9) return ch[0] == '+' ? Max : Min;
res += (ch[i] - '0') * carry;
carry *= 10;
}
return ch[0] == '-' ? -res : res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: