天天看點

Quicksum

/*
*程式的版權和版本聲明部分:
*Copyright(c)2014,煙台大學計算機學院學生
*All rights reserved.
*檔案名稱:
*作者:田成琳
*完成日期:2014 年 6 月 12 日
*版本号:v1.0
*對任務及求解方法的描述部分:
*問題描述: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 exampleQuicksum 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

*程式輸入: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.

*程式輸出:For each packet, output its Quicksum on a separate line in the output.
*問題分析:
*算法設計:
*/
           

題目分析:題中意思說輸入案例有多個,每個輸入案例中隻包含大寫字母和空格,然後根據每個大寫字母的位置做相應計算。A=1,B=2,C=3...,Z=26。比如ACM:A在第一位,C第二位,M第三位,那麼結果就為1*1+2*3+3*13=46。但應引起注意的是案例中有的有空格字元,空格字元看成0對待。那麼實作代碼如下:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
    char word[100000];
    int sum,length,i;
    while(cin.getline(word,sizeof(word))&&(string)word!="#")//運用類型轉換
    {
        sum=0;
        length=strlen(word);
        for(i=0; i<length; i++)
        {
            while(word[i]==' ')//忽略空格
                i++;
            sum+=(i+1)*(int)(word[i]-64);//類型轉換
        }
        cout<<sum<<endl;
    }
    return 0;
}
           

運作結果:

Quicksum