免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
123456
最近访问板块 发新帖
楼主: zephyr82
打印 上一主题 下一主题

[求助] 有点难度D,请老大们指点 [复制链接]

论坛徽章:
0
51 [报告]
发表于 2004-06-17 15:43 |只看该作者

[求助] 有点难度D,请老大们指点

flw的xADD算法太复杂了。按照这个思路,下面是我的简化版本。


  1. //return '0' if out of range
  2. inline char safechar(const char *str, int idx)
  3. {
  4.         return idx < 0 ? '0'  : str[idx];
  5. }

  6. //a + b = p
  7. bool XAdd(char * p, const char *a, const char *b)
  8. {
  9.        
  10.         size_t alen = strlen(a);
  11.         size_t blen = strlen(b);
  12.         size_t biglen = alen >; blen ? alen : blen;
  13.         int carry = 0, tmpindex, aindex, bindex;       
  14.         char temp[MAX_LEN + 2];  //extra 2 chars from overflow and null-terminated
  15.         temp[MAX_LEN + 1] = '\0';
  16.        
  17.         //locate to last indx we are going to calc
  18.         tmpindex = MAX_LEN;
  19.         aindex = alen - 1;
  20.         bindex = blen - 1;
  21.         for(int i = 0; i < biglen; ++i, --tmpindex)
  22.         {
  23.                 temp[tmpindex] = safechar(a, aindex--) + safechar(b, bindex--) - '0' + carry;
  24.                 if ( temp[tmpindex] >; '9' )
  25.                 {
  26.                         temp[tmpindex] -= 10;
  27.                         carry = 1;
  28.                 }
  29.                 else
  30.                         carry = 0;
  31.         }

  32.         if(carry)
  33.                 temp[tmpindex] = '1';
  34.         else
  35.                 tmpindex++;

  36.         if(tmpindex == 0)
  37.                 return false;                //overflow, highest is used

  38.         strcpy(p, temp + tmpindex);

  39.         return true;
  40. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP