练练手,题目出自
两个大数相乘:char* multiply(char*,char*)。给了两个字符串,每个都是代表了一个很长的10进制表示的数, 比如 String str1 = "23456789009877666555544444"; String str2 = "346587436598437594375943875943875", 最后求出它们的乘积。 不用jdk的数学运算包BigInteger.或者类似的包。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MULTIPLY_SIZE 200 int m_atoi(char c); char *multiply(char *s, char *muldstr, char *mulerstr); char *reverse_string(char *str); //ascii to char int m_atoi(char c){ return ((c>='0')&&(c<='9'))? (c-'0') : 0; } char *multiply(char *s, char *muldstr, char *mulerstr){ int muldlen = strlen(muldstr); int mulerlen = strlen(mulerstr); int count = 0; int i, j; for(i=muldlen-1; i>=0; i--, count++){ char *ptrs = s + count; int carrier = 0; int muld = m_atoi(muldstr[i]); for(j=mulerlen-1; j>=0; j--){ int mul, temp, mod; temp = (m_atoi(*ptrs)+carrier); mul = m_atoi(mulerstr[j]); temp = temp + muld * mul; *ptrs = temp % 10 + '0'; carrier = temp/10; ptrs++; } if(carrier != 0){ *ptrs = carrier + '0'; } } reverse_string(s); return s; } char *reverse_string(char *s){ int len = strlen(s); char *first = s; char *last = s + len -1; while(last > first){ char c = *first; *first = *last; *last = c; first++; last--; } return s; } int main(int argc, char *argv[]){ /* char s1[200]; char s2[200]; char *s; scanf_s("%s", s1, sizeof(s1)); scanf_s("%s", s2, sizeof(s2)); */ char s1[200] = "23456789009877666555544444"; char s2[200] = "346587436598437594375943875943875"; char *s; s = (char *)malloc(sizeof(char)*MULTIPLY_SIZE); memset(s, 0, MULTIPLY_SIZE); multiply(s, s1, s2); printf("%s\n", s); free(s); system("pause"); return 0; }
8129828373763903512004369615410968394975299532195012080500