H-08

    xiaoxiao2021-03-25  134

    Description

    In the 22nd Century, scientists have discovered intelligent residents live on the Mars. Martians are very fond of mathematics. Every year, they would hold an Arithmetic Contest on Mars (ACM). The task of the contest is to calculate the sum of two 100-digit numbers, and the winner is the one who uses least time. This year they also invite people on Earth to join the contest. As the only delegate of Earth, you're sent to Mars to demonstrate the power of mankind. Fortunately you have taken your laptop computer with you which can help you do the job quickly. Now the remaining problem is only to write a short program to calculate the sum of 2 given numbers. However, before you begin to program, you remember that the Martians use a 20-based number system as they usually have 20 fingers. Input: You're given several pairs of Martian numbers, each number on a line. Martian number consists of digits from 0 to 9, and lower case letters from a to j (lower case letters starting from a to present 10, 11, ..., 19). The length of the given number is never greater than 100. Output: For each pair of numbers, write the sum of the 2 numbers in a single line. Sample Input: 1234567890 abcdefghij 99999jjjjj 9999900001 Sample Output: bdfi02467j iiiij00000 题目描述: 给你几组20进制的数,求两个数相加的和。 解题思路: 用字符串形式输入,然后将其转化成数字,最后在将10以上的数用字符输出。如果两个数相加超过19,那么就要向下一位产生进位。 解题细节: 别忘了考虑两个字符串的长度,注意两字符串不一样长时的运算,最后要反向输出字符串。 代码: #include<bits/stdc++.h> using namespace std; char a[105],b[105]; int r[105]; int s(char d)//用来输出时转为字符。 { if(d>='0'&&d<='9') return d-'0'; else if(d>='a'&&d<='j') return d-'a'+10; } char q(int i)//输入时转为数字。 { if(i>=0&&i<=9) return '0'+i; else if(i>=10&&i<=19) return 'a'+i-10; } int main() { int len1,len2,len3; int i,j; char c; while(cin>>a>>b) { len1=strlen(a); len2=strlen(b); memset(r,0,sizeof(r)); for(i=0;i<len1/2;i++) { c=a[i]; a[i]=a[len1-1-i]; a[len1-1-i]=c; } for(i=0;i<len2/2;i++) { c=b[i]; b[i]=b[len2-1-i]; b[len2-1-i]=c; } for(i=0;i<min(len1,len2);i++)//当均小于两个字符串长度时的运算 { r[i]=s(a[i])+s(b[i]); } for(i=min(len1,len2);i<max(len1,len2);i++)//当大于较小字符串长度时的运算 { if(len1>len2) r[i]=s(a[i]); else       r[i]=s(b[i]);         }         len3=i;         for(i=0;i<len3;i++)         {             if(r[i]>=20)             {                 r[i+1]++;                 r[i]-=20;            }        }         if(r[len3]!=0)             len3++;         for(i=len3-1;i>=0;i--)             cout<<q(r[i]);         cout<<endl;     }     return 0; } 心得体会: 要有耐心,头脑清楚。
    转载请注明原文地址: https://ju.6miu.com/read-5274.html

    最新回复(0)