POJ3094 Quicksum

POJ3094 Quicksum
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18517   Accepted: 12712

Description

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 = 46

MID CENTRAL: 1*13 + 2*9 + 3*4 + 4*0 + 5*3 + 6*5 + 7*14 + 8*20 + 9*18 + 10*1 + 11*12 = 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

Source

 
题目分析:
 
     计算只含[大写字母+空格]的字符串的校验和.
     其中每个字母有其对应的特征值,空格=0,A=1,B=2,...,Z=26
     校验和 = 所有 [字符的位置(从1开始) * 字母特征值] 之和
 
#include <memory.h>
#include <iostream>
using namespace std;
 
 
// 被校验字符串的最大长度
const static int MAX_LEN = 255;
 
int getFeatureVal(char c);
 
 
int main(void) {
    char str[MAX_LEN] = { '' };
    while(true) {
        gets(str);  // 输入字符串中包含空格,不能用cin接收
        int len = strlen(str);
        if(strlen(str) <= 0 || str[0] == '#') {
            break;
        }
 
        int quicksum = 0;
        for(int i = 0; i < len; i++) {
            quicksum += ((i + 1) * getFeatureVal(str[i]));
        }
        cout << quicksum << endl;
 
        memset(str, '', sizeof(char) * len);
    }
    return 0;
}
 
 
int getFeatureVal(char c) {
    return (c == ' ' ? 0 : (c - 'A' + 1));
} 
原文地址:https://www.cnblogs.com/alan-blog-TsingHua/p/10640145.html