任意大的自然数相乘,谁愿意完成其他工作?

Chrisma 2003-05-12 11:46:31
#include <stdio.h>
#include <string.h>
class NUMBER{
char *n;
public:
NUMBER(char *n);
NUMBER(NUMBER const &a);
~NUMBER();
NUMBER operator+(const NUMBER &a) const;
NUMBER operator*(const NUMBER &a) const;
NUMBER operator++(int);
NUMBER & operator=(const NUMBER &a);
NUMBER &operator++();
operator const char *()const;
};
NUMBER &NUMBER::operator++(){
*this=*this+"1";
return *this;
}
NUMBER NUMBER::operator++(int){
NUMBER r(*this);
*this=*this+"1";
return r;
}
NUMBER::NUMBER(char *n){
if(NUMBER::n=new char[strlen(n)+1]) strcpy(NUMBER::n, n);
}
NUMBER::NUMBER(const NUMBER &a){
if(n=new char[strlen(a.n)+1]) strcpy(n, a.n);
}
NUMBER::~NUMBER(){
if(n) { delete n; n=0; }
}
NUMBER &NUMBER::operator=(const NUMBER &a){
delete n;
if(n=new char[strlen(a.n)+1]) strcpy(n, a.n);
return *this;
}
NUMBER NUMBER::operator+(const NUMBER &a) const{
int m, c=0, p=strlen(n), q=strlen(a.n);
if(p>q) m=p; else m=q; m+=2;
char *t=new char[m]; t[--m]=0;
while (p>0 && q>0){
c=c+n[--p]+a.n[--q]-2*'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)? 1: 0;
}
while (p>0){
c=c+n[--p]-'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)?1: 0;
}
while (q>0){
c=c+a.n[--q]-'0';
t[--m]=((c>=10)?c-10: c)+'0';
c=(c>=10)?1: 0;
}
if(c>0) {t[--m]='1'; }
NUMBER x(t+m);
delete t;
return x;
}

NUMBER NUMBER::operator*(const NUMBER &a) const{
int v,w, c, p=strlen(n), q=strlen(a.n);
NUMBER r("");
NUMBER b((p>q)?n:a.n);
NUMBER m((p>q)?a.n:n);
for(v=0, w=((p>q)?q:p); v<w; v++){
char *t=new char[strlen(r.n)+2];
r=strcat(strcpy(t, r.n), "0");
delete t;
for(c=m[v]-'0'; c>0; c--) r=r+b;
}
if (strlen(r)==0) return NUMBER("0");
return r;
}

NUMBER::operator const char *() const{
return n;
}

void main(){
NUMBER x("12345678924124232142142341242133324345342434235190909034");
NUMBER y("9876543213453665575673653653343453434097857623432332324");
++x;
printf("%s\n", x);
++ ++x;
printf("%s\n", x);
printf(x*y);
}
...全文
27 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Chrisma 2003-05-13
  • 打赏
  • 举报
回复
改成支持负整数的+,-,*, /,%等方法
Berton2L 2003-05-13
  • 打赏
  • 举报
回复
还要做什么??

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧