Created
March 12, 2013 15:53
-
-
Save sooop/5144058 to your computer and use it in GitHub Desktop.
bignum.c - add very large number using strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
// basic function | |
char * reverse(const char* s1); | |
int __strlen(const char *s1); | |
char * ljust(const char *s1, int length, char c); | |
char * ltrim(const char *s1, char c); | |
int max(int a, int b); | |
// operation function | |
char * stradd(const char *s1, const char *s2); | |
char * strmpl(const char *s1, const char *s2); | |
int main(int argc, const char * args) | |
{ | |
printf("%s\n", stradd("3423223525626543452634587454438454552534457432453446565445556456","3428256342344523335644534523453547576845623423423451234534563456") ); | |
return 0; | |
} | |
// implementation operation fucntion | |
char * stradd(const char *s1, const char *s2) | |
{ | |
int maxLen = max(strlen(s1), strlen(s2)) + 1; | |
char *a1 = ljust(reverse(s1), maxLen, '0'); | |
char *a2 = ljust(reverse(s2), maxLen, '0'); | |
// '0' --> 48, '9' --> 57 | |
char *r = (char*)malloc(maxLen+1 * sizeof(char)); | |
r[maxLen] = 0; | |
int i, temp=0; | |
for (i=0;i<maxLen;i++) | |
{ | |
int v = (a1[i]-48)+(a2[i]-48)+temp; | |
if(v>9) {temp = v % 10; v = v /10; } else {temp = 0; } | |
r[i] = v+48; | |
} | |
r = ltrim(reverse(r),'0'); | |
free(a1); | |
free(a2); | |
return r; | |
} | |
// implemetation basic function | |
int max(int a, int b){if(a-b >=0){return a;} return b; } | |
char * reverse(const char *s1) | |
{ | |
int l = strlen(s1); | |
char *r = (char *)malloc((l+1)*sizeof(char)); // alloc one more byte for null-ending charactor | |
r[l] = 0; | |
int i; | |
for(i=l;i>0;i--) {r[l-i] = s1[i-1]; } | |
return r; | |
} | |
char * ljust(const char *s1, int length, const char c) | |
{ | |
int l = strlen(s1); | |
char *r = (char*)malloc((length+1)*sizeof(char)); | |
if(r==NULL){return NULL;} | |
r[length] = '\0'; | |
int i=0; | |
while(i<length) | |
{ | |
if(i<l) {r[i] = s1[i]; } | |
else {r[i] = c; } | |
i++; | |
} | |
return r; | |
} | |
char * ltrim(const char *s1,const char c) | |
{ | |
int i = 0; | |
int l = strlen(s1); | |
while(s1[i] == c && i < l) {i++;} | |
if(i==l) return NULL; | |
char *r = (char *)malloc((l-i+1) * sizeof(char)); | |
r[l-i] = 0; | |
memcpy(r,s1+i,l-i); | |
return r; | |
} | |
void __initchars(char* s1, int len) {int i; for(i=0;i<len;i++) {s1[i] = 0;} } | |
int __strlen(const char *s1) {int i=0; while(s1[i] != 0) {i++; } return i; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment