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


  • this method calculates sum of digits in string of length 10. string has of form "12345?789x" or "12?4567890", '?' can lie anywhere , has value of 0, 'x' (if present) lies @ end of string , equal 10.
  • the sum should calculated follows: "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 numbers ending 'x', don't, returns value of sum 0. example, "111?111111" instead of returning 48, returns 0.
  • i'm not able find out 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; } 

i wrote test , it's green:

@test public void removeme() {     string input = "111?111111";     int sum = 0;     int temp = 0;     for(int = 0; < input.length(); i++){         char = 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 remove argument l , use input.length(), did.


Comments