حساب مجموع جميع الأرقام الموجودة في السلسلة

حساب مجموع جميع الأرقام الموجودة في السلسلة
جربه على ممارسة GfG #practiceLinkDiv { العرض: لا شيء! مهم؛ }

نظرا لسلسلة س تحتوي على أحرف أبجدية رقمية وتتمثل المهمة في حساب مجموع جميع الأرقام الموجودة في السلسلة.

أمثلة:  

مدخل:  1abc23
الإخراج: 24
توضيح: 1 + 23 = 24

مدخل:  geeks4geeks
الإخراج: 4

مدخل:  1abc2x30yz67
الإخراج: 100

الممارسة الموصى بها مجموع الأرقام في السلسلة جربه!

يقترب:

قم بمسح كل حرف من سلسلة الإدخال وإذا تم تشكيل رقم بواسطة أحرف متتالية من السلسلة، فقم بزيادة نتيجة بهذا المبلغ. الجزء الوحيد الصعب في هذا السؤال هو أن الأرقام المتتالية المتعددة تعتبر رقمًا واحدًا.

اتبع الخطوات التالية لتنفيذ الفكرة:

  • إنشاء سلسلة فارغة درجة حرارة وعدد صحيح مجموع .
  • التكرار على كافة أحرف السلسلة.
    • إذا كان الحرف رقمًا رقميًا، فأضفه إليه درجة حرارة .
    • وإلا قم بتحويل السلسلة المؤقتة إلى رقم وإضافتها إلى مجموع فارغ درجة حرارة .
  • مجموع الإرجاع + الرقم الذي تم الحصول عليه من درجة الحرارة.

وفيما يلي تنفيذ النهج المذكور أعلاه:

C++
   // C++ program to calculate sum of all numbers present   // in a string containing alphanumeric characters   #include          using     namespace     std  ;   // Function to calculate sum of all numbers present   // in a string containing alphanumeric characters   int     findSum  (  string     str  )   {      // A temporary string      string     temp     =     ''  ;      // holds sum of all numbers present in the string      int     sum     =     0  ;      // read each character in input string      for     (  char     ch     :     str  )     {      // if current character is a digit      if     (  isdigit  (  ch  ))      temp     +=     ch  ;      // if current character is an alphabet      else     {      // increment sum by number found earlier      // (if any)      sum     +=     atoi  (  temp  .  c_str  ());      // reset temporary string to empty      temp     =     ''  ;      }      }      // atoi(temp.c_str()) takes care of trailing      // numbers      return     sum     +     atoi  (  temp  .  c_str  ());   }   // Driver code   int     main  ()   {      // input alphanumeric string      string     str     =     '12abc20yz68'  ;      // Function call      cout      < <     findSum  (  str  );      return     0  ;   }   
Java
   // Java program to calculate sum of all numbers present   // in a string containing alphanumeric characters   import     java.io.*  ;   class   GFG     {      // Function to calculate sum of all numbers present      // in a string containing alphanumeric characters      static     int     findSum  (  String     str  )      {      // A temporary string      String     temp     =     '0'  ;      // holds sum of all numbers present in the string      int     sum     =     0  ;      // read each character in input string      for     (  int     i     =     0  ;     i      <     str  .  length  ();     i  ++  )     {      char     ch     =     str  .  charAt  (  i  );      // if current character is a digit      if     (  Character  .  isDigit  (  ch  ))      temp     +=     ch  ;      // if current character is an alphabet      else     {      // increment sum by number found earlier      // (if any)      sum     +=     Integer  .  parseInt  (  temp  );      // reset temporary string to empty      temp     =     '0'  ;      }      }      // atoi(temp.c_str()) takes care of trailing      // numbers      return     sum     +     Integer  .  parseInt  (  temp  );      }      // Driver code      public     static     void     main  (  String  []     args  )      {      // input alphanumeric string      String     str     =     '12abc20yz68'  ;      // Function call      System  .  out  .  println  (  findSum  (  str  ));      }   }   // This code is contributed by AnkitRai01   
Python3
   # Python3 program to calculate sum of   # all numbers present in a string   # containing alphanumeric characters   # Function to calculate sum of all   # numbers present in a string   # containing alphanumeric characters   def   findSum  (  str1  ):   # A temporary string   temp   =   '0'   # holds sum of all numbers   # present in the string   Sum   =   0   # read each character in input string   for   ch   in   str1  :   # if current character is a digit   if   (  ch  .  isdigit  ()):   temp   +=   ch   # if current character is an alphabet   else  :   # increment Sum by number found   # earlier(if any)   Sum   +=   int  (  temp  )   # reset temporary string to empty   temp   =   '0'   # atoi(temp.c_str1()) takes care   # of trailing numbers   return   Sum   +   int  (  temp  )   # Driver code   # input alphanumeric string   str1   =   '12abc20yz68'   # Function call   print  (  findSum  (  str1  ))   # This code is contributed   # by mohit kumar   
C#
   // C# program to calculate sum of   // all numbers present in a string   // containing alphanumeric characters   using     System  ;   class     GFG     {      // Function to calculate sum of      // all numbers present in a string      // containing alphanumeric characters      static     int     findSum  (  String     str  )      {      // A temporary string      String     temp     =     '0'  ;      // holds sum of all numbers      // present in the string      int     sum     =     0  ;      // read each character in input string      for     (  int     i     =     0  ;     i      <     str  .  Length  ;     i  ++  )     {      char     ch     =     str  [  i  ];      // if current character is a digit      if     (  char  .  IsDigit  (  ch  ))      temp     +=     ch  ;      // if current character is an alphabet      else     {      // increment sum by number found earlier      // (if any)      sum     +=     int  .  Parse  (  temp  );      // reset temporary string to empty      temp     =     '0'  ;      }      }      // atoi(temp.c_str()) takes care of trailing      // numbers      return     sum     +     int  .  Parse  (  temp  );      }      // Driver code      public     static     void     Main  (  String  []     args  )      {      // input alphanumeric string      String     str     =     '12abc20yz68'  ;      // Function call      Console  .  WriteLine  (  findSum  (  str  ));      }   }   // This code is contributed by PrinciRaj1992   
JavaScript
    <  script  >   // Javascript program to calculate   // sum of all numbers present   // in a string containing    // alphanumeric characters          // Function to calculate sum       // of all numbers present      // in a string containing       // alphanumeric characters      function     findSum  (  str  )      {      // A temporary string      let     temp     =     '0'  ;          // holds sum of all numbers       // present in the string      let     sum     =     0  ;          // read each character in input string      for     (  let     i     =     0  ;     i      <     str  .  length  ;     i  ++  )     {      let     ch     =     str  [  i  ];          // if current character is a digit      if     (  !  isNaN  (  String  (  ch  )     *     1  ))      temp     +=     ch  ;          // if current character is an alphabet      else     {      // increment sum by number found earlier      // (if any)      sum     +=     parseInt  (  temp  );          // reset temporary string to empty      temp     =     '0'  ;      }      }          // atoi(temp.c_str()) takes care of trailing      // numbers      return     sum     +     parseInt  (  temp  );      }          // Driver code      // input alphanumeric string      let     str     =     '12abc20yz68'  ;          // Function call      document  .  write  (  findSum  (  str  ));       // This code is contributed by unknown2108    <  /script>   

الإخراج
100 


تعقيد الوقت: O(N) حيث n هو طول السلسلة. 
المساحة المساعدة: O(N) حيث n هو طول السلسلة.

حساب مجموع جميع الأرقام الموجودة في سلسلة باستخدام العودية

والفكرة هي اجتياز السلسلة بشكل متكرر ومعرفة أرقام ثم قم بإضافة هذه الأرقام إلى نتيجة في النهاية إرجاع نتيجة

اتبع الخطوات التالية لتنفيذ الفكرة:

  • إنشاء سلسلة فارغة درجة حرارة وعدد صحيح مجموع .
  • اجتياز الأحرف بشكل متكرر لكل فهرس أنا من ل الطول - 1 .
    • لو ط = ن-1 ثم تحقق مما إذا كان الحرف الحالي عبارة عن إرجاع أرقام شارع [i] - '0' .
    • وإلا ارجع .
    • لو شارع [أنا] هو رقم.
      • قم بتشغيل حلقة for مع العداد ي  من أنا ل ن - 1 .
        • إذا كان الحرف رقمًا رقميًا، فأضفه إليه درجة حرارة .
        • وإلا استراحة.
      • يعود مجموع للقيمة الرقمية لدرجة الحرارة + التكرار للفهرس ي .

وفيما يلي تنفيذ النهج المذكور أعلاه:

C++
   // C++ program to calculate sum of all numbers   // present in a string containing alphanumeric   // characters   #include          using     namespace     std  ;   int     solve  (  string  &     str       int     i       int     n  )   {      // if string is empty      if     (  i     >=     n  )      return     0  ;      // if on the last index      if     (  i     ==     n     -     1  )     {      // if last digit is numeric      if     (  isdigit  (  str  [  i  ]))     {      return     str  [  i  ]     -     '0'  ;      }      else     {      return     0  ;      }      }      // if current char is digit      // then sum the consecutive digits      if     (  isdigit  (  str  [  i  ]))     {      // declared an empty string      string     temp     =     ''  ;      int     j  ;      // start from that index      // sum all the consecutive digits      for     (  j     =     i  ;     j      <     n  ;     j  ++  )     {      // if current char is digit      // add it to the temp string      if     (  isdigit  (  str  [  j  ]))      temp     +=     str  [  j  ];      // if it is not a digit      // break instantly      else      break  ;      }      // add the number associated to temp      // with the answer recursion will bring      return     stoi  (  temp  )     +     solve  (  str       j       n  );      }      // else call from the next index      else     {      solve  (  str       i     +     1       n  );      }   }   int     findSum  (  string     str  )   {      // recursiven function      return     solve  (  str       0       str  .  size  ());   }   // Driver code   int     main  ()   {      // input alphanumeric string      string     str     =     '12abc20yz68'  ;      // Function call      cout      < <     findSum  (  str  );      return     0  ;   }   
Java
   import     java.util.Scanner  ;   class   Main     {      static     int     solve  (  String     str       int     i       int     n  )     {      // if string is empty      if     (  i     >=     n  )      return     0  ;      // if on the last index      if     (  i     ==     n     -     1  )     {      // if last digit is numeric      if     (  Character  .  isDigit  (  str  .  charAt  (  i  )))     {      return     str  .  charAt  (  i  )     -     '0'  ;      }      else     {      return     0  ;      }      }      // if current char is digit      // then sum the consecutive digits      if     (  Character  .  isDigit  (  str  .  charAt  (  i  )))     {      // declared an empty string      String     temp     =     ''  ;      int     j  ;      // start from that index      // sum all the consecutive digits      for     (  j     =     i  ;     j      <     n  ;     j  ++  )     {      // if current char is digit      // add it to the temp string      if     (  Character  .  isDigit  (  str  .  charAt  (  j  )))      temp     +=     str  .  charAt  (  j  );      // if it is not a digit      // break instantly      else      break  ;      }      // add the number associated to temp      // with the answer recursion will bring      return     Integer  .  parseInt  (  temp  )     +     solve  (  str       j       n  );      }      // else call from the next index      else     {      return     solve  (  str       i     +     1       n  );      }      }      static     int     findSum  (  String     str  )     {      // recursiven function      return     solve  (  str       0       str  .  length  ());      }      // Driver code      public     static     void     main  (  String  []     args  )     {      // input alphanumeric string      String     str     =     '12abc20yz68'  ;      // Function call      System  .  out  .  println  (  findSum  (  str  ));      }   }   // This code contributed by Ajax   
Python3
   def   findSum  (  str  ):   # variable to store sum   result   =   0   temp   =   ''   for   i   in   range  (  len  (  str  )):   if   str  [  i  ]  .  isnumeric  ():   temp   +=   str  [  i  ]   if   i   ==   len  (  str  )   -   1  :   result   +=   int  (  temp  )   else  :   if   temp   !=   ''  :   result   +=   int  (  temp  )   temp   =   ''   return   result   # driver code   if   __name__   ==   '__main__'  :   # input alphanumeric string   str   =   '12abc20yz68'   print  (  findSum  (  str  ))   #This code contributed by Shivam Tiwari   
C#
   // C# program to calculate sum of all numbers   // present in a string containing alphanumeric   // characters   using     System  ;   using     System.Linq  ;   using     System.Collections.Generic  ;   class     GFG      {      static     bool     isdigit  (  char     c  )      {      if  (  c  >=  '0'     &&     c   <=  '9'  )      return     true  ;      return     false  ;      }      static     int     solve  (  string     str       int     i       int     n  )      {      // if string is empty      if     (  i     >=     n  )      return     0  ;          // if on the last index      if     (  i     ==     n     -     1  )     {          // if last digit is numeric      if     (  isdigit  (  str  [  i  ]))     {      return     str  [  i  ];      }      else     {      return     0  ;      }      }          // if current char is digit      // then sum the consecutive digits      if     (  isdigit  (  str  [  i  ]))     {          // declared an empty string      string     temp     =     ''  ;      int     j  ;          // start from that index      // sum all the consecutive digits      for     (  j     =     i  ;     j      <     n  ;     j  ++  )     {          // if current char is digit      // add it to the temp string      if     (  isdigit  (  str  [  j  ]))      temp     +=     str  [  j  ];          // if it is not a digit      // break instantly      else      break  ;      }          // add the number associated to temp      // with the answer recursion will bring      return     Int32  .  Parse  (  temp  )     +     solve  (  str       j       n  );      }          // else call from the next index      else     {      return     solve  (  str       i     +     1       n  );      }      }          static     int     findSum  (  string     str  )      {      // recursiven function      return     solve  (  str       0       str  .  Length  );      }          // Driver code      static     public     void     Main  ()      {      // input alphanumeric string      string     str     =     '12abc20yz68'  ;          // Function call      Console  .  Write  (  findSum  (  str  ));          }   }   
JavaScript
   function     findSum  (  str  )     {      // variable to store sum      let     result     =     0  ;      let     temp     =     ''  ;          for     (  let     i     =     0  ;     i      <     str  .  length  ;     i  ++  )     {      if     (  !  isNaN  (  str  [  i  ]))     {      temp     +=     str  [  i  ];      if     (  i     ===     str  .  length     -     1  )     {      result     +=     parseInt  (  temp  );      }      }     else     {      if     (  temp     !==     ''  )     {      result     +=     parseInt  (  temp  );      temp     =     ''  ;      }      }      }      return     result  ;   }   // driver code   console  .  log  (  findSum  (  '12abc20yz68'  ));   // This code is contributed by Shivam Tiwari   

الإخراج
100 

تعقيد الوقت: على) حيث N هو حجم السلسلة المحددة.
المساحة المساعدة: على) في أسوأ الحالات يمكن أن يكلف O(N) مكالمات متكررة

احسب مجموع جميع الأرقام الموجودة في سلسلة باستخدام Regex في Python:

والفكرة هي استخدام وظيفة يحمل في ثناياه عوامل بايثون ريجيكس . 

فيما يلي تنفيذ النهج أعلاه:

C++14
   #include          #include         // Function to calculate sum of all   // numbers present in a string   // containing alphanumeric characters   int     findSum  (  std  ::  string     str  )     {      // Regular Expression that matches      // digits in between a string      std  ::  regex     pattern  (  '  \  d+'  );      std  ::  smatch     match  ;      int     sum     =     0  ;      while     (  std  ::  regex_search  (  str       match       pattern  ))     {      sum     +=     stoi  (  match  [  0  ].  str  ());      str     =     match  .  suffix  ().  str  ();      }      return     sum  ;   }   // Driver code   int     main  ()     {      // input alphanumeric string      std  ::  string     str     =     '12abc20yz68'  ;      // Function call      std  ::  cout      < <     findSum  (  str  )      < <     std  ::  endl  ;      return     0  ;   }   // This code is contributed by Shivam Tiwari   
Python3
   # Python3 program to calculate sum of   # all numbers present in a string   # containing alphanumeric characters   # Function to calculate sum of all   # numbers present in a string   # containing alphanumeric characters   import   re   def   find_sum  (  str1  ):   # Regular Expression that matches   # digits in between a string   return   sum  (  map  (  int     re  .  findall  (  'd+'     str1  )))   # Driver code   # input alphanumeric string   str1   =   '12abc20yz68'   # Function call   print  (  find_sum  (  str1  ))   # This code is contributed   # by Venkata Ramana B   
JavaScript
   // JavaScript program to calculate sum of   // all numbers present in a string   // containing alphanumeric characters   // Function to calculate sum of all   // numbers present in a string   // containing alphanumeric characters   function     find_sum  (  str1  )     {      // Regular Expression that matches      // digits in between a string      return     str1  .  match  (  /d+/g  ).  reduce  ((  acc       val  )     =>     acc     +     parseInt  (  val  )     0  );   }   // Driver code   // input alphanumeric string   const     str1     =     '12abc20yz68'  ;   // Function call   console  .  log  (  find_sum  (  str1  ));   
Java
   import     java.util.regex.*  ;   public     class   Main     {      // Function to calculate sum of all      // numbers present in a string      // containing alphanumeric characters      public     static     int     findSum  (  String     str  )      {      // Regular Expression that matches      // digits in between a string      Pattern     pattern     =     Pattern  .  compile  (  '\d+'  );      Matcher     matcher     =     pattern  .  matcher  (  str  );      int     sum     =     0  ;      while     (  matcher  .  find  ())     {      sum     +=     Integer  .  parseInt  (  matcher  .  group  ());      str     =     matcher  .  replaceFirst  (  ''  );      matcher     =     pattern  .  matcher  (  str  );      }      return     sum  ;      }      // Driver code      public     static     void     main  (  String  []     args  )      {      // input alphanumeric string      String     str     =     '12abc20yz68'  ;      // Function call      System  .  out  .  println  (  findSum  (  str  ));      }   }   
C#
   using     System  ;   using     System.Text.RegularExpressions  ;   public     class     GFG   {      // Function to calculate sum of all      // numbers present in a string      // containing alphanumeric characters      public     static     int     FindSum  (  string     str  )      {      // Regular Expression that matches      // digits in between a string      Regex     pattern     =     new     Regex  (  @'d+'  );      Match     matcher     =     pattern  .  Match  (  str  );      int     sum     =     0  ;      while     (  matcher  .  Success  )      {      sum     +=     Int32  .  Parse  (  matcher  .  Value  );      str     =     pattern  .  Replace  (  str       ''       1       matcher  .  Index  );      matcher     =     pattern  .  Match  (  str  );      }      return     sum  ;      }      // Main method      static     public     void     Main  ()      {      // input alphanumeric string      string     str     =     '12abc20yz68'  ;      // Function call      Console  .  WriteLine  (  FindSum  (  str  ));      }   }   

الإخراج
100 

تعقيد الوقت: O(n) حيث n هو طول السلسلة. 
المساحة المساعدة: O(n) حيث n هو طول السلسلة.