首頁  >  文章  >  後端開發  >  給定一個字串,求其中連續數字所組成的數的總和

給定一個字串,求其中連續數字所組成的數的總和

王林
王林轉載
2023-08-28 09:17:14659瀏覽

給定一個字串,求其中連續數字所組成的數的總和

問題陳述

We have given a string str containing the numeric and alphabetical characters. We need to find the sum of all numbers represented by a continuous sequence of digits available in the given string.

範例範例

Input

str = “12were43”

輸出

55

Explanation

The sum of 12 and 43 is equal to 55.

Input

str = “1a2c3d”

輸出

6

Explanation

1、2和3的和為6。

Input

str = “werderfrewsf”

輸出

0

Explanation

It gives 0 in the output as the string contains no digit.

我們解決問題的邏輯是從給定的字串中提取所有數字並求和。

方法一

In this approach, we will use isDigit() method to check whether the current character is a digit. Also, we multiply the current value of the number by 10 and add the current character to the number of the current by 10 and add the current character to the number ifacter to the number the current a digit.

演算法

  • 步驟 1 - 將 'number' 和 'sum' 變數初始化為零。

  • Step 2 − Iterate through the string and check current character is between 0-9 using the isDigit() method.

  • 步驟 3 - 如果目前字元是數字,則將數字值乘以10,並加上目前數字值。

  • 第四步 - 如果目前字元不是數字,則將「number」變數的值加到「sum」變數中,並將「number」變數的值更新為零。

  • Step 5 − Once the iteration of the loop completes, add the value of the 'number' to the 'sum' variable and return the value of the sum variable.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive number present in the string
int getSumOfDigits(string str){
   // store the current number
   int number = 0;
   // Stores total sum
   int sum = 0;
   // Traverse the string
   for (auto &ch : str){
      // If the current character is between '0' and '9', append it to the number
      if (isdigit(ch)) {
         number = number * 10 + ch - '0';
      } else {
         // 	if the current character is not between '0' and '9', add 'number' to the sum and reset 'number'
         sum += number;
         number = 0;
      }
   }
   // if the number is greater than 0, add it to sum
   sum += number;
   return sum;
}
int main(){
   string str = "6we24er5rd6";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

輸出

The sum of consecutive digits in the given string is - 41
  • 時間複雜度 - O(n),因為我們只使用了一個迴圈。

  • 空間複雜度 − O(1),因為我們不使用任何額外的空間。

Approach 2

In this approach, we use the ASCII values of the character to check whether the current character is a digit. Also, we append characters to the 'number' variable until we get digits in the string and meth the atoi() the atoil we get digits in the string and meth the atoi( to extract the number from the string.

演算法

  • 步驟1 - 定義'number'變數並將其初始化為空字串。同時,定義'sum'變數並將其初始化為0。

  • Step 2 − Use for loop to traverse the string and get each character of the string.

  • 步驟 3 - 如果 c-‘0’ 大於等於零且小於等於 9,則表示目前字元是一個數字。

  • Step 4 − If the current character is a digit, append it to the ‘number’ string.

  • Step 5 − If the current character is not a digit, use the c_str() method to convert the number string to a character array and pass it as a parameter of the atoi() method to convert the string to a number. Also, update the number string with the “” value.

    The atoi() method returns a number if the string is convertible to a number; Otherwise, it returns zero.

  • Step 6 − Once the iteration of for loop completes, again use the atoi() method to convert the string to a number and add to the sum value.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive numbers present in the string
int getSumOfDigits(string str){
   string number = "";
   // to store the sum of all the consecutive numbers
   int sum = 0;
   // traverse the string
   for (char c : str){
      // if the current character is between 0 to 9
      if (c - '0' >= 0 && c - '0' <= 9){
         // append it to the number string
         number += c;
      }
      // if the current character is an alphabet
      else {
         // convert string to an array of characters and pass it to atoi() function
         sum += atoi(number.c_str());
         // reset temporary string to empty
         number = "";
      }
   }
   // if the number is greater than 0, add it to sum
   sum += atoi(number.c_str());
   return sum;
}
int main(){
   string str = "11aa32bbb5";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

輸出

The sum of consecutive digits in the given string is - 48
  • 時間複雜度 - O(N)

  • 空間複雜度 − O(1)

方法三

在這個方法中,我們使用正規表示式來找到所有數字的匹配項。之後,我們可以將字串轉換為數字並將其添加到sum變數中。

演算法

  • Step 1 − Define the regex pattern.

  • #Step 2 − Use the regex_search() method to find the match for the number string.

  • #Step 3 − Make iterations using a while loop as long as we find matches.

  • #Step 4 − In the while loop, use the stoi() method to convert the string to a number and add it to the sum variable.

  • 第5步 - 同樣,使用match().suffix()方法更新字串。這樣我們就不會得到重複的匹配。

Example

#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum of the numbers found in the string
int getSumOfDigits(string str){
   // regex pattern to find the numbers in the string
   regex pattern("d+");
   smatch match;
   // variable to store the sum of the numbers
   int sum = 0;
   // using the regex_search() function to find the numbers
   while (regex_search(str, match, pattern)){
      // adding the numbers to the sum variable
      sum += stoi(match[0].str());
      // update the string
      str = match.suffix().str();
   }
   return sum;
}
int main(){
   // input alphanumeric string
   string str = "abc23@12";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

輸出

The sum of consecutive digits in the given string is - 0
  • Time complexity − O(N), as regex finds matches by iterating through the string.

  • 空間複雜度 − O(1)

Conclusion

我們學習了三種不同的方法來找出字串中連續數字的和。最後一種方法是最優化的程式碼,因為它使用了正規表示式。然而,對於初學者來說,使用正規表示式可能會很困難。

以上是給定一個字串,求其中連續數字所組成的數的總和的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除