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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP