C++ 字串中字元字母值的總和


在這個問題中,我們得到一個字串陣列 str[]。我們的任務是找到陣列中所有字串的得分。得分定義為字串位置與字串字元字母值之和的乘積。

讓我們舉個例子來理解這個問題:

輸入

str[] = {“Learn”, “programming”, “tutorials”, “point” }

說明

“Learn” 的位置 − 1 →

sum = 12 + 5 + 1 + 18 + 14 = 50. Score = 50

“programming” 的位置 − 2 →

sum = 16 + 18 + 15 + 7 + 18 + 1 + 13 + 13 + 9 + 14 + 7 = 131
Score = 262

“tutorials” 的位置 − 1 →

sum = 20 + 21 + 20 + 15 + 18 + 9 + 1 + 12 +
19 = 135
Score = 405

“point” 的位置 − 1 →

sum = 16 + 15 + 9 + 14 + 20 = 74
Score = 296

為了解決這個問題,一個簡單的方法是遍歷陣列的所有字串。對於每個字串,儲存其位置並找到字串的字母值之和。將位置和總和相乘並返回乘積。

演算法

步驟 1 − 遍歷字串並存儲每個字串的位置,然後執行步驟 2 和 3 −

步驟 2 − 計算字串中字母的總和。

步驟 3 − 列印位置和總和的乘積。

示例

程式演示上述解決方案的工作原理:

線上演示

#include <iostream>
using namespace std;
int strScore(string str[], string s, int n, int index){
   int score = 0;
   for (int j = 0; j < s.length(); j++)
      score += s[j] - 'a' + 1;
   score *= index;
   return score;
}
int main(){
   string str[] = { "learn", "programming", "tutorials", "point" };
   int n = sizeof(str) / sizeof(str[0]);
   string s = str[0];
   for(int i = 0; i<n; i++){
      s = str[i];
      cout<<"The score of string ' "<<str[i]<<" ' is "<<strScore(str, s, n, i+1)<<endl;
   }
   return 0;
}

輸出

The score of string ' learn ' is 50
The score of string ' programming ' is 262
The score of string ' tutorials ' is 405
The score of string ' point ' is 296

更新於:2020年8月6日

1K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告