码迷,mamicode.com
首页 > 编程语言 > 详细

EOJ 3037: 十六进制加法(高精度+数组位运算)

时间:2019-03-03 17:33:25      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:over   pre   eof   while   crossover   取字符串   array   data   its   

一、思路:

1.字符数组读入,整形数组存储,字符数组输出

2.类似于十进制大数加法,用整型数组模拟运算;总使得长度长的字符串作为s1,这涉及到字符数组交换

3.每次结束时清空整型数组

二、注意点:

1.读取时采用:

scanf("%s%s",s1+1,s2+1);

获取字符串长度采用:

len1=strlen(s1+1);
len2=strlen(s2+1);

交换字符串采用:

char temp[205];
strcpy(temp+1,s1+1);
strcpy(s1+1,s2+1);
strcpy(s2+1,temp+1);

这里所有的字符数组都是从第1位而非第0位开始存储

2.模拟加法过程中,使尾部对齐,向前运算;注意j的大小,否则会造成数组越界;最后通过判断a[0]是否大于0来考虑是否增长len1,整体后移:

void getAnswer(int a[], int b[])
{
    for(int i=len1, j=len2;i>=1;--i,--j){
        a[i]+=(j>=1)?b[j]:0;//notice here whether j>=1, or it will cause array crossover
        if(a[i]>=16){
            a[i-1]+=1;
            a[i]%=16;
        }
    }
    if(a[0]){
        len1++;
        for(int i=len1;i>=1;--i)
            a[i]=a[i-1];
    }
}

三、代码:

#include <bits/stdc++.h>
using namespace std;
//hexadecimal addition

char s1[205], s2[205];
int a[205], b[205];
int T, cnt, len1, len2;

int char2int(char ch)
{
    if(ch>=0&&ch<=9) return ch-0;
    else return ch-A+10;
}

char int2char(int x)
{
    if(x<10) return x+0;
    else return x-10+A;
}

void getAnswer(int a[], int b[])
{
    for(int i=len1, j=len2;i>=1;--i,--j){
        a[i]+=(j>=1)?b[j]:0;//notice here whether j>=1, or it will cause array crossover
        if(a[i]>=16){
            a[i-1]+=1;
            a[i]%=16;
        }
    }
    if(a[0]){
        len1++;
        for(int i=len1;i>=1;--i)
            a[i]=a[i-1];
    }
}
int main()
{
    cin>>T;
    while(T--){
        scanf("%s%s",s1+1,s2+1);
        if(strlen(s1+1)<strlen(s2+1)){//if len1<len2, swap s1 and s2
            char temp[205];
            strcpy(temp+1,s1+1);
            strcpy(s1+1,s2+1);
            strcpy(s2+1,temp+1);
        }
        len1=strlen(s1+1);
        len2=strlen(s2+1);

        //use int array to store data
        for(int i=1;i<=len1;++i)
            a[i]=char2int(s1[i]);
        for(int i=1;i<=len2;++i)
            b[i]=char2int(s2[i]);
        getAnswer(a,b);
        printf("case #%d:\n",cnt++);
        for(int i=1;i<=len1;++i)
            cout<<int2char(a[i]);
        cout<<endl;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
    }
    return 0;
}

 

EOJ 3037: 十六进制加法(高精度+数组位运算)

标签:over   pre   eof   while   crossover   取字符串   array   data   its   

原文地址:https://www.cnblogs.com/ChenyangXu/p/10466508.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!