面試題是我找的,代碼也看了,但是代碼我自己寫的!!!
//大數相加,相減 相除 相乘
#include <iostream>
using namespace std;
//此轉換只是在特定條件下的 int類型只有0-9
inline int num(char s){return s-'0';}//char轉換成int
inline char ch(int num){return num+'0';}//int轉換成char
char * add(char a[],char b[]);
char c[100] ={'0'};
void main()
{
char a[100] ={'0'} ; //保存第一個數
char b[100] = {'0'}; //保存第二個數
while(1){
memset(a,'\0',100);
memset(b,'\0',100);
//i=1,j=1,保留符號位+和-
int i=1,j=1;
cout<<" 根據提示輸入整數,輸入非數字程序將會中止退出! "<<endl;
cout<<"請輸入第一個數字:";
//獲取符號位
a[0]=getchar();
if(a[0] > '9'&&a[0] < '0'&&a[0] != '-'&&a[0] != '+')continue;
else if(a[0] == '-')a[0] ='-';
else if ( a[0]>='0' && a[0]<='9')
{a[1] =a[0];a[0] = '+';i++;}
while ( (a[i]=getchar()) !='\n' )
{
if ( a[i]>'9' && a[i]<'0')break;
else{
i++;
}
}
a[i]='\0';
cout<<"請輸入第二個數字:";
//獲取符號位
b[0]=getchar();
if(b[0] > '9'&&b[0] < '0'&&b[0] != '-'&&b[0] != '+')continue;
else if(b[0] == '-')b[0] ='-';
else if ( b[0]>='0' && b[0]<='9')
{b[1] =b[0];b[0] = '+';j++;}
while ( (b[j]=getchar()) !='\n' )
{
if ( b[j]>'9' && b[j]<'0')break;
else{
j++;
}
}
b[j]='\0';
cout<<a;
cout<<b<<endl;
cout<<add(a,b)<<endl;
}
system("pause");
}
char * add(char a[],char b[])
{
int l =strlen(a)-1;
int r =strlen(b)-1;
int result;
int overflow =0;
if(l>=r)
{
for(int i=l;i>0;i--)
{
if(i>l-r){
result =(num(a[i])+num(b[i-l+r])+overflow)%10;
overflow =(num(a[i])+num(b[i-l+r])+overflow)/10;
a[i] = ch(result);
}
else{
result =(num(a[i])+overflow)%10;
overflow =(num(a[i])+overflow)/10;
a[i] = ch(result);
if(i==1&&overflow!=0)
{
memset(c,'\0',100);
c[0] =a[0];
c[1] =ch(overflow);
for(int s =1;s<=l;s++)
c[s+1]=a[s];
return c;
}
}
}
return a;
}else
{
for(int i=r;i>0;i--)
{
if(i>r-l){
result =(num(b[i])+num(a[i-r+l])+overflow)%10;
overflow =(num(b[i])+num(a[i-r+l])+overflow)/10;
b[i] = ch(result);
}
else{
result =(num(b[i])+overflow)%10;
overflow =(num(b[i])+overflow)/10;
b[i] = ch(result);
if(i==1&&overflow!=0)
{
memset(c,'\0',100);
c[0] =b[0];
c[1] =ch(overflow);
for(int s =1;s<=l;s++)
c[s+1]=b[s];
return c;
}
}
}
return b;
}
}