大数加法和比较。。C的缺点就是数据结构全要自己实现啊,最基本的自增长list都木有,悲催,代码全是纯手工打造。。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reverse1962(char *s)
{
int len = strlen(s);
int i, j;
char c;
for (i = 0, j = len - 1; i < j; i++, j--)
{
c = *(s + i);
*(s + i) = *(s + j);
*(s + j) = c;
}
}
char *add1962(char *s1, char *s2)
{
int l1 = strlen(s1);
int l2 = strlen(s2);
int len = l1 > l2 ? l1 : l2;
char *r = malloc(len + 2);
int i, prev = 0, a, b, sum;
for (i = 0; i < len; i++)
{
a = l1 - 1 - i >= 0 ? *(s1 + l1 - 1 - i) - '0' : 0;
b = l2 - 1 - i >= 0 ? *(s2 + l2 - 1 - i) - '0' : 0;
sum = a + b + prev;
*(r + i) = sum > 9 ? sum - 10 + '0' : sum + '0';
prev = sum > 9 ? 1 : 0;
}
if (prev)
{
*(r + len) = '1';
*(r + len + 1) = '\0';
}
else
*(r + len) = '\0';
reverse1962(r);
return r;
}
int compareInteger(char *s1, char *s2)
{
int l1 = strlen(s1);
int l2 = strlen(s2);
if (l1 != l2)
return l1 - l2;
else
for (; *s1 != '\0'; s1++, s2++)
if (*s1 != *s2)
return *s1 - *s2;
return 0;
}
struct StringList
{
char **array;
int capacity;
int total;
};
typedef struct StringList *strlistptr;
strlistptr newStringList(int capacity)
{
strlistptr p = malloc(sizeof(struct StringList));
p->total = 0;
p->capacity = capacity;
p->array = malloc(capacity * sizeof(char *));
return p;
}
void addString(char *string, strlistptr p)
{
if (p->total == p->capacity)
{
p->capacity *= 2;
char **newArray = realloc(p->array, (sizeof(char *)) * p->capacity);
p->array = newArray;
}
char **array = p->array;
*(array + p->total) = string;
p->total++;
}
void freeStringList(strlistptr p)
{
free(p->array);
free(p);
}
int main()
{
char *f1 = "1";
char *f2 = "2";
char *temp;
strlistptr p = newStringList(500);
addString(f1, p);
addString(f2, p);
while (strlen(f2) <= 100)
{
temp = add1962(f1, f2);
addString(temp, p);
f1 = f2;
f2 = temp;
}
char s1[102], s2[102];
while (scanf("%s %s", s1, s2), strcmp(s1, "0") || strcmp(s2, "0"))
{
int i, count = 0;
for (i = 0; i < p->total; i++)
if (compareInteger(*(p->array + i), s1) >= 0
&& compareInteger(*(p->array + i), s2) <= 0)
count++;
printf("%d\n",count);
}
freeStringList(p);
return 0;
}