大數減法
阿新 • • 發佈:2018-08-06
n) stdlib.h spa ems subst inpu 大數 cati set
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define MaxSize 1000 bool _TwoSubStrcmp(char* Minuend,char* Subtrahend) { int MinuendLen = strlen(Minuend); int SubtrahendLen = strlen(Subtrahend); if(MinuendLen > SubtrahendLen)return true; else if(MinuendLen == SubtrahendLen) return (strcmp(Minuend,Subtrahend)>0); else if(MinuendLen < SubtrahendLen) return false; } char *_TwoBigNumSub(char *InputMinuend,char *InputSubtrahend) { char *Result = malloc(MaxSize*sizeof(char)); int ResultEnd = 0; int MinuendLen = strlen(InputMinuend); int SubtrahendLen = strlen(InputSubtrahend); int Minuend[MaxSize]; int Subtrahend[MaxSize]; memset(Minuend,0,sizeof(Minuend)); memset(Subtrahend,0,sizeof(Subtrahend)); //reverse to store int InputSubend,SubendEnd;for(InputSubend = MinuendLen-1,SubendEnd = 0;InputSubend >= 0;InputSubend --) { Minuend[SubendEnd ++] = InputMinuend[InputSubend] - ‘0‘; } for(InputSubend = SubtrahendLen-1,SubendEnd = 0;InputSubend >= 0;InputSubend --) { Subtrahend[SubendEnd ++] = InputSubtrahend[InputSubend] - ‘0‘; } //Sub && Abdicate int Abdication = 0; for(SubendEnd = 0;SubendEnd < MaxSize;SubendEnd ++) { Minuend[SubendEnd] -= Abdication; if(Minuend[SubendEnd] < Subtrahend[SubendEnd]) { Minuend[SubendEnd] += 10; Abdication = 1; } else { Abdication = 0; } Subtrahend[SubendEnd] = Minuend[SubendEnd] - Subtrahend[SubendEnd]; } //store to return //0 screening for(SubendEnd = MaxSize-1;SubendEnd>=0 && Subtrahend[SubendEnd]==0;SubendEnd --) ; if(SubendEnd >= 0) { for( ;SubendEnd >= 0;SubendEnd --) { Result[ResultEnd++] = Subtrahend[SubendEnd] + ‘0‘; } } else { Result[ResultEnd++] = ‘0‘; } Result[ResultEnd] = ‘\0‘; return Result; } char *TwoBigNumSub(char *InputMinuend,char *InputSubtrahend) { char *TempResult; char *Result = malloc(MaxSize*sizeof(char)); int ResultEnd = 0; int TempResultEnd = 0; if(_TwoSubStrcmp(InputMinuend,InputSubtrahend)==true) { TempResult = _TwoBigNumSub(InputMinuend,InputSubtrahend); } else { Result[ResultEnd++] = ‘-‘; TempResult = _TwoBigNumSub(InputSubtrahend,InputMinuend); } for(TempResultEnd = 0;TempResultEnd < MaxSize;TempResultEnd ++) { Result[ResultEnd++] = TempResult[TempResultEnd]; } free(TempResult); return Result; } int main() { char InputMinuend[MaxSize] = "5"; char InputSubtrahend[MaxSize] = "692355225511444222555"; char *Result = TwoBigNumSub(InputMinuend,InputSubtrahend); puts(Result); return 0; }
大數減法