版权声明:本文为HCG原创文章,未经博主允许不得转载。请联系[email protected] https://blog.csdn.net/qq_39455116/article/details/82755469
【题目】
给定一个字符串 str, 求其中 全部数字串 所代表的数字之和。
【要求】
l. 忽略小数点字符, 例如 'A l . 3" , 其中包含两 个数字 1 和 3。
2. 如果紧贴数字子串的左侧出现字符 '-" ’ 当连续出现的数量为奇数时, 则数字视为负,连续出现的数械为偶数 时, 则数字视为正。例如, " A- I BC–12",
其中包含数字为4 和 1 2。
【举例】
stt= “Al CD2E33” , 返回 36。
package string;
import java.lang.reflect.Array;
import java.util.Arrays;
public class ShuZiTotal {
public Integer total(String str){
//总的和
Integer total =0;
//用于标记字符串中的数字是否是正数
Boolean b =true ;
//临时的数字字符串
Integer nowNum = 0;
char [] arr = str.toCharArray();
Integer temp =0 ;
for (int i =0 ;i<arr.length ;i++){
nowNum =(int)arr[i]- (int)'0' ;
if(arr[i] =='-'){
b=false;
}else if (nowNum <=9 && nowNum >=0){
System.out.println(nowNum);
temp =temp*10+nowNum ;
}else {
if(b ==true){
total =temp+total;
}else {
total =-temp+total ;
}
//这里如果当前字符不是-也不是数字的话,把临时数字加到total里面
//同时把b重置为true
temp=0;
b =true;
}
}
if(temp!= 0){
total =total+temp;
}
System.out.println("----------------");
return total ;
}
public static void main(String[] args) {
ShuZiTotal shuZiTotal =new ShuZiTotal();
System.out.println(shuZiTotal.total("-A-11-C1D-s136"));
}
}