Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String (containing characters and integers) to integers and calculating the sum in JAVA

  • This method calculates the sum of all digits in a String of length 10. The String has to be of the form "12345?789x" or "12?4567890", where '?' can lie anywhere and has a value of 0, 'x' (if present) lies at the end of the String and is equal to 10.
  • The sum should be calculated as follows: For "11432?789x", sum = (10*1)+(9*1)+(8*4)+(7*3)+(6*2)+(5*0)+(4*7)+(3*8)+(2*9)+(1*10) = 164.
  • This code works perfectly for numbers ending with 'x', but for those that don't, it returns the value of sum as 0. For example, for "111?111111" instead of returning 48, it returns 0.
  • I'm not able to find out the error. Please help.

    public static int sum(String input,int l){
    int sum=0;
    int temp=0;
    char a;
    for(int i=0;i<l;i++){
        a=input.charAt(i);
        if(a=='x'){
            temp=10;
        }
         else if(a=='?'){
            temp=0;
        }
        else{
        temp = Character.getNumericValue(input.charAt(i));
        }
    
    
        sum = temp*(10-i)+sum;
    }
    return sum;
    }
    
like image 806
ryan321 Avatar asked Feb 10 '23 13:02

ryan321


2 Answers

I wrote this test and it's green:

@Test
public void removeme() {
    String input = "111?111111";
    int sum = 0;
    int temp = 0;
    for(int i = 0; i < input.length(); i++){
        char a = input.charAt(i);
        if(a == 'x'){
            temp = 10;
        } else if(a == '?'){
            temp = 0;
        } else {
            temp = Character.getNumericValue(input.charAt(i));
        }

        sum = temp * (10 - i) + sum;
    }
    assertThat(sum , is(48));
}

I suggest you remove the argument l and just use input.length(), as I did.

like image 161
Manu Avatar answered Apr 27 '23 23:04

Manu


Your example:

111?111111

Expected result: 48

if I call:

String input = "111?111111";
int result = sum(input,input.length());

result is 48

Maybe you call method like this:

String input = "111?111111";
int result = sum(input,0);

There result is 0

Or second parameter of sum is corrupted.

like image 34
maskacovnik Avatar answered Apr 27 '23 23:04

maskacovnik