-3

how to get the sum of no which contains 8 digit in array? For example we take input from user and stored in array i.e. 33,6,8,95,123,88 so the sum will be 8+88=96 ......So how to find out the array contains 8 digit .Whats the logic behind this ...can anybody explain this?

  • 2
    How would you as a human solve that? How do you know which of the numbers contains the digit 8? – Thomas Feb 06 '18 at 13:59
  • I don't know the exact logic that's why I posted this question yesterday – Devashish Suthar Feb 07 '18 at 14:22
  • Well, I as a human would look at the numbers and sum those that contain at least one 8. From that you can see a simple logic: (1) look at each number, (2) if the number has an 8 in it (3) add it to the sum. Now translate that to code and youz have a loop over the array (1), a check for digits (2) and add the number (3). For step (2) there are several ways but those are easy to find via google. – Thomas Feb 07 '18 at 14:27
  • Thank you thomas. Now its simple for me to find out the exact logic – Devashish Suthar Feb 07 '18 at 14:29

1 Answers1

0

If you facing this kind of problem try to divide it into small parts and then try to solve them. In the end they will exhaustively solve the big problem.

By the way You can do this in 2 ways in java.

Split number into digit using modulus (% ) operator.

for ( int I = 0; i<arr.length ; i++){
        value = arr[i]; 
        while( value > 0 ){
            if ( value%10 == 8 ){
               //  it contains 8.
               // add arr[i] to total  and break the loop
             }
            Value= value/10;
       }
    }

eg :- 108%10 = 8

convert your number in to String and use String#toCharArray() to split it.

 String value = String.valueOf( arr[i] );  // convert it to char array
 Char [] digitList = value.toCharArray();  // add separate digit to char array

And then check the char array has digit 8.

For more on spiting digits view this question's answers.

dilusha_dasanayaka
  • 1,401
  • 2
  • 17
  • 30