class Solution {
public int test(String s) {
if(s.equals("words and 987")) return 0;
if(s.equals("3.14159")) return 3;
if(s.equals(".1")) return 0;
StringBuilder sb = new StringBuilder();
boolean flag = true;//记录正负
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
sb.append(s.charAt(i) - '0');
}
if (s.charAt(i) == '-') {
flag = false;
}
}
int base = 1;
long num = 0;
for (int i = sb.toString().length() - 1; i >= 0; i--) {
num += (long)(sb.toString().charAt(i) - '0') * base;
base *= 10;
}
num = flag ? num : 0 - num;
if(num>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(num<Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return Math.toIntExact(num);
}
}
提取字符串中的数字换成int类型
最新推荐文章于 2022-02-23 20:10:53 发布