字符串表示的大整数相加

 

int revstr(char *str)
{
    char ch;
    char *start = str;
    char *end = str;
    if(str == NULL)
        return -1;
    while(*end)
        end++;
    end -= 1;
    while(start < end)
    {
        ch = *start;
        *start++ = *end;
        *end-- = ch;
    }
    return 0;
}
int bigNumAdd(char *strNum1,char *strNum2, char *strRslt)            // 大整数相乘  
{  
    int i,j, carry,t,rslt_index = 0;  
    char chx, chy;
    if(strNum1 == NULL || strNum2 == NULL || strRslt == NULL)
        return -1;
    i = strlen(strNum1) - 1;
    j = strlen(strNum2) - 1;
    memset(strRslt, 0 ,((i > j) ? i : j) + 2);//把存放结果的空间先清零
    carry = 0;
    while(i >= 0 || j >= 0)
    {   
        chx = (i < 0)? 0:strNum1[i] - '0';
        chy = (j < 0)? 0:strNum2[j] - '0';
        t = chx + chy + carry;//从最低位开始计算                             
        strRslt[rslt_index++] = t % 10 + '0';      
        carry = t / 10;  
        i--;
        j--;
    }
    if(carry > 0)
        strRslt[rslt_index] += carry + '0';  
    revstr(strRslt);
    return 0;
}  

 

posted on 2013-09-18 23:17  swblog  阅读(390)  评论(0编辑  收藏  举报

导航