【HDU1002】A + B Problem II(大数加法)

Categories: 数据结构和算法
Tags: ,
Comments: No Comments
Published on: 2011 年 09 月 15 日

本来退役考研了,但是此生有幸进入区域赛场地赛,所以复出几天以了没参加过真正ACM的遗憾。从水题开始练练编码,顺便写俩常用代码。
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
数字字符串数组转化为整型数组:

int str2num(char* str,int* arr){
	int len=0;
	for (int i=0;str[i]!='\0';i++){
		len++;
		arr[i]=str[i]-48;
	}
	return len;
}

递归实现数组颠倒逆序:

template<class T>
void reverse(T *arr,int len){
	char temp;
	if(len<=1) return;
	temp=*arr; *arr=*(arr+len-1); *(arr+len-1)=temp;
	reverse(arr+1,len-2);
}

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxlen 1005
int a[maxlen],b[maxlen];
int str2num(char* str,int* arr){
	int len=0;
	for (int i=0;str[i]!='\0';i++){
		len++;
		arr[i]=str[i]-48;
	}
	return len;
}
template<class T>
void reverse(T *arr,int len){
	char temp;
	if(len<=1) return;
	temp=*arr; *arr=*(arr+len-1); *(arr+len-1)=temp;
	reverse(arr+1,len-2);
}

char temp[maxlen];
int main(){
	int n,loop,lena,lenb,len,p,first=0;
	scanf("%d",&n);
	loop=n;
	while(n--){
		if(first!=0) puts("");
		first=1;
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		printf("Case %d:\n",loop-n);
		scanf("%s",temp);
		printf("%s + ",temp);
		lena=str2num(temp,a);
		reverse(a,lena);
		scanf("%s",temp);
		printf("%s = ",temp);
		lenb=str2num(temp,b);
		reverse(b,lenb);
		len= lena>lenb?lena:lenb;
		p=0;
		for (int i=0;i<len;i++){
			a[i]=a[i]+b[i]+p;
			p=a[i]/10;
			a[i]=a[i]%10;
		}
		if(p!=0) a[len++]=p;
		for(int i=len-1;i>=0;i--){
			printf("%d",a[i]);
		}
		puts("");
	}
}

我猜你可能也喜欢:

No Comments - Leave a comment

Leave a comment

电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Welcome , today is 星期二, 2017 年 10 月 24 日