VJ_QE
VJ_QE

Reputation: 143

Write java program to sum of all integers from a random String

I was asked this question in an interview recently (Java programming que)

I was allowed to use any inbuilt functions as well

I wrote this code , however this seems little more complex. Can this code be done any other way?

public int convertString(String str){
int num=0, currNo = 0;
Boolean isNegative = false;

for (int i=0 ; i<str.length(); i++){
Char t = str.charAt(i) ;

    if(t == ‘-‘){
       if(isNegative)
            num = num-currNo;
        else
            num = num + currNo;

       isNegative=true;
       currNo=0;
    }
    else if(((t-‘0’) <= 9 && (t-‘0’)>=0)){
        currNo = (currNo*10) + t;
    }
    else {

            if(isNegative)
            num = num-currNo;
        else
            num = num + currNo;

        currNo=0;
        isNegative=false;
    }
}


if(isNegative)
            num = num-currNo;
        else
            num = num + currNo;                         
isNegative=true;

return num;
}

Upvotes: 0

Views: 814

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53839

Using regex:

Matcher m = Pattern.compile("-?\\d+").matcher(str);
long sum = 0;
while(m.find()) {
    sum += Integer.parseInt(m.group());
}

Upvotes: 8

Related Questions