【acm2734】 Realtime Status

问题:
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the packet is changed, the checksum will also change, so checksums are often used for detecting transmission errors, validating document contents, and in many other situations where it is necessary to detect undesirable changes in data.
For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only uppercase letters and spaces. It always begins and ends with an uppercase letter. Otherwise, spaces and letters can occur in any combination, including consecutive spaces.
A Quicksum is the sum of the products of each character’s position in the packet times the character’s value. A space has a value of zero, while letters have a value equal to their position in the alphabet. So, A=1, B=2, etc., through Z=26. Here are example Quicksum calculations for the packets “ACM” and “MID CENTRAL”:
ACM: 1
1 + 2
3 + 3
13 = 46MID CENTRAL: 1
13 + 2
9 + 3
4 + 40 + 53 + 65 + 714 + 820 + 918 + 101 + 1112 = 650

Input
The input consists of one or more packets followed by a line containing only # that signals the end of the input. Each packet is on a line by itself, does not begin or end with a space, and contains from 1 to 255 characters.

Output
For each packet, output its Quicksum on a separate line in the output.

Sample Input
ACM
MID CENTRAL
REGIONAL PROGRAMMING CONTEST
ACN
A C M
ABC
BBC

Sample Output
46
650
4690
49
75
14
15******

代码:

#include<iostream>
#include<cstring>
using namespace std;
char s[999];
int main(){
	while(gets(s)){
		if(strcmp(s,"#")==0){
			break;
		}
			int sum=0;
	for(int i=0;i<strlen(s);i++){
		
	    if(s[i]-'A'>=0){
	    	sum+=(s[i]-'A'+1)*(i+1);
		}
	}
	cout<<sum<<endl;
	}
	
	

	return 0;

}

**
代码:这里要注意的是输入带有空格的字符串,所以单纯的使用cin输入字符创或者字符数组是会出现错误的,所以这里建议使用①gets(str)或者②cin.getline(str)函数。同时注意的是如果为空格要特殊处理。因为空格的ascii码是32,小于字母的所以这里可以直接判断是否大于A,或者直接判断是否为空格,但是需要多开辟一个空间来保存。
**

发布了27 篇原创文章 · 获赞 17 · 访问量 171

猜你喜欢

转载自blog.csdn.net/weixin_42918559/article/details/104012815