题目链接在此☞http://acm.hdu.edu.cn/showproblem.php?pid=1002
这题也比较简单,只需要开三个长度为1000的char数组来分别储存a、b、ans,再利用我们加法的算法,先向右对齐再相加。注意一下进位时的特殊情况就好了。
不过笔者的代码写好后提交上去,两次Presentation Error,然后才发现只是最后多输出一个空行的问题 =。= Orz
代码语言:javascript复制/**
* HDOJ 1002 A B Problem II
* Big Numbers Addition (using String)
* Time Cost : O(n)
* Author: Zheng Chen / Arclabs001
* Copyright 2015 Xi'an University of Posts & Telecommunications. All rights reserved.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
//String a and b contains two number and this function compare which one is bigger.
//If a is larger, return true, else false.
bool compare(char *a, char *b, size_t len_a, size_t len_b)
{
if(len_a != len_b)
return len_a > len_b;
for(size_t i=0; i<len_a; i )
{
if(a[i] != b[i])
return a[i] > b[i];
}
return true;
}
//If a is not larger than b, then swap a and b.
void swap(char *a, char *b, size_t len_a, size_t len_b)
{
char tmp[1002];
memset(tmp,0,sizeof(tmp));
size_t i;
for(i=0; i<len_a; i )
{
tmp[i] = a[i];
}
tmp[i] = '