Advertisement
bozhilov

ROITI Find sum of numbers in String O(n)/O(n^2)

Mar 15th, 2022 (edited)
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. public class Digits {
  2.    
  3.     public static double getDigits(String s){
  4.         double sum = 0;
  5.         String temp = "";
  6.         CharSequence seq = ".";
  7.         for (int i = 0; i < s.length(); i++) {
  8.             if((Character.isDigit(s.charAt(i)) || s.charAt(i) == '.') && i!=s.length()-1){
  9.                 if(temp=="" && s.charAt(i) == '.'){
  10.                     continue;
  11.                 } else if(temp.contains(seq) && s.charAt(i) == '.') throw new NumberFormatException("Unformatted Input");
  12.                 // this check makes the algorithm O(n^2) in the worst possible case, otherwise it is O(n)
  13.                 // it is not O(n(nm)) (Boyer-Moore) , because the char sequence is only '.'
  14.                 temp+=s.charAt(i);
  15.             } else {
  16.                 if(Character.isDigit(s.charAt(i)) && i==s.length()-1) temp+=s.charAt(i);
  17.                 try{sum+=Double.parseDouble(temp);}
  18.                 catch(Exception e){}
  19.                 temp="";
  20.             }
  21.         }
  22.         return sum;
  23.     }
  24.    
  25.  
  26.     public static void main(String[] args){
  27.         String s = "2 beers0.5 or not 12.3 beers.5";
  28.         try{
  29.         System.out.println(getDigits(s));
  30.         } catch(Exception e){
  31.             System.out.println(e.getMessage());
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement