- 论坛徽章:
- 0
|
[求助] 有点难度D,请老大们指点
flw的xADD算法太复杂了。按照这个思路,下面是我的简化版本。
- //return '0' if out of range
- inline char safechar(const char *str, int idx)
- {
- return idx < 0 ? '0' : str[idx];
- }
- //a + b = p
- bool XAdd(char * p, const char *a, const char *b)
- {
-
- size_t alen = strlen(a);
- size_t blen = strlen(b);
- size_t biglen = alen >; blen ? alen : blen;
- int carry = 0, tmpindex, aindex, bindex;
- char temp[MAX_LEN + 2]; //extra 2 chars from overflow and null-terminated
- temp[MAX_LEN + 1] = '\0';
-
- //locate to last indx we are going to calc
- tmpindex = MAX_LEN;
- aindex = alen - 1;
- bindex = blen - 1;
- for(int i = 0; i < biglen; ++i, --tmpindex)
- {
- temp[tmpindex] = safechar(a, aindex--) + safechar(b, bindex--) - '0' + carry;
- if ( temp[tmpindex] >; '9' )
- {
- temp[tmpindex] -= 10;
- carry = 1;
- }
- else
- carry = 0;
- }
- if(carry)
- temp[tmpindex] = '1';
- else
- tmpindex++;
- if(tmpindex == 0)
- return false; //overflow, highest is used
- strcpy(p, temp + tmpindex);
- return true;
- }
复制代码 |
|