- 论坛徽章:
- 0
|
原帖由 windaoo 于 2009-7-29 02:18 发表 ![]()
呵呵,短一点的版本:
char *fun(char *s)
{
int i = strlen(s);
while (i-- && s == '9' ? s = '0' : (s += 1, 0)) ...
这个程序有个问题,当被加字符串全为9时,就得不到正确的值的。
下边是一个支持任意两个整数字符串相加的程序,
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <assert.h>
- char * add_str(const char *s1, const char *s2)
- {
- int len1 = strlen(s1);
- int len2 = strlen(s2);
- char *a1 = malloc(len1 + 2);
- char *a2 = malloc(len2 + 2);
- char *result = malloc((len1 > len2 ? len1 : len2) + 1);
- int carry = 0;
- int i = 0, j = -1, t;
- /* Use leading 0 as sentinel. */
- sprintf(a1, "0%s", s1);
- sprintf(a2, "0%s", s2);
- while (len1 || len2) {
- result[i++] = (carry + a1[len1] + a2[len2] - 2 * '0') % 10 + '0';
- carry = (carry + a1[len1] + a2[len2] - 2 * '0') / 10;
- if (len1) len1--;
- if (len2) len2--;
- }
- if (carry)
- result[i++] = carry + '0';
- result[i] = 0;
- /* Reverse the result. */
- while (++j < --i) {
- t = result[j];
- result[j] = result[i];
- result[i] = t;
- }
- free(a1);
- free(a2);
- return result;
- }
- int main()
- {
- char a[100];
- char b[100];
- char *r;
- while (1) {
- printf("Please input integer a ans b:\n");
- scanf("%s%s", a, b);
- r = add_str(a, b);
- printf("%s + %s = %s\n", a, b, r);
- free(r);
- }
- return 0;
- }
复制代码 |
|