iamaamir

Sum Of String Values

Jul 17th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1.  
  2. /**
  3.  *
  4.  * @author Aamir khan
  5.  */
  6. public class SumOfStrings {
  7.  
  8.     /**
  9.      * @author Aamir khan
  10.      */
  11.     public static void main(String[] args) {
  12.  
  13.         //direct sum
  14.         System.out.println(
  15.                 "123".chars().map(i -> Character.digit(i, 10)).sum()
  16.         );
  17.  
  18.         //filter numeric values
  19.         System.out.println(
  20.                 "123four".chars().filter(SumOfStrings::isNum).map(i -> Character.digit(i, 10)).sum()
  21.         );
  22.  
  23.         //old school solution
  24.         int sum = 0;
  25.         for (char c : "four321".toCharArray()) {
  26. //            if (c < 48 || c > 58) continue;
  27.             if (!isNum(c)) continue;
  28.             sum += Character.digit(c, 10);
  29.         }
  30.         System.out.println(sum);
  31.     }
  32.  
  33.     private static boolean isNum(int c){
  34.         return Character.isDigit(c);
  35.     }
  36. }
Add Comment
Please, Sign In to add comment