首页 > 代码库 > 大整数加法与减法
大整数加法与减法
模拟运算
用数组逆向保存大数每一位 加法直接从尾向前相加(尾部已对齐) 注意进位
减法类似 确保大数减小数 不够减了向前减一 需要注意符号的有无问题
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 using namespace std; 5 6 int a[11000], b[11000]; 7 string s1, s2; 8 9 void Add() 10 { 11 int len1 = s1.length(); 12 int len2 = s2.length(); 13 int Max = max(len1, len2); 14 int k; 15 for (int i = len1-1, k = 0; i >= 0; i--) 16 a[k++] = s1[i] - ‘0‘; 17 for (int i = len2-1, k = 0; i >= 0; i--) 18 b[k++] = s2[i] - ‘0‘; 19 20 if (a[0] == 0 && b[0] == 0) { 21 cout << ‘0‘; 22 return; 23 } 24 int up = 0; 25 for (int i = 0; i < Max+1; i++) { 26 a[i] = a[i] + b[i] + up; 27 up = a[i] / 10; 28 a[i] %= 10; 29 } 30 int first; 31 for (first = Max+1; first >= 0; first--) 32 if (a[first]) 33 break; 34 35 for (int i = first; i >= 0; i--) 36 cout << a[i]; 37 38 } 39 40 void Sub(string Max, string Min) //a - b 41 { 42 int len1 = Max.length(); 43 int len2 = Min.length(); 44 int MaxLen = max(len1, len2); 45 46 int k; 47 for (int i = len1-1, k = 0; i >= 0; i--) 48 a[k++] = Max[i] - ‘0‘; 49 for (int i = len2 - 1, k = 0; i >= 0; i--) 50 b[k++] = Min[i] - ‘0‘; 51 52 int up = 0; 53 for (int i = 0; i < MaxLen+1; i++) { 54 a[i] = a[i] - b[i] - up; 55 if (a[i] < 0) { 56 up = 1; 57 a[i] += 10; 58 } 59 else 60 up = 0; 61 } 62 63 int first; 64 for (first = MaxLen+1; first >= 0; first--) 65 if (a[first]) 66 break; 67 68 if (first == -1) 69 cout << "0"; 70 else { 71 for (int i = first; i >= 0; i--) 72 cout << a[i]; 73 } 74 } 75 76 int main() 77 { 78 cin >> s1 >> s2; 79 80 memset(a, 0, sizeof(a)); 81 memset(b, 0, sizeof(b)); 82 83 if (s1[0] == ‘-‘ && s2[0] == ‘-‘) 84 { 85 cout << ‘-‘; 86 s1.erase(0, 1); 87 s2.erase(0, 1); 88 Add(); 89 } 90 else if (s1[0] == ‘-‘ || s2[0] == ‘-‘) 91 { 92 string Max, Min; 93 if (s1[0] == ‘-‘) { 94 if (s1.length()-1 > s2.length()) 95 cout << "-"; 96 if (s1.length()-1 == s2.length()) 97 { 98 if (s1[1] > s2[0]) 99 cout << "-"; 100 } 101 s1.erase(0, 1); 102 } 103 104 if (s2[0] == ‘-‘) { 105 106 if (s2.length()-1 > s1.length()) 107 cout << "-"; 108 if (s1.length() == s2.length()-1) 109 { 110 if (s2[1] > s1[0]) 111 cout << "-"; 112 } 113 s2.erase(0, 1); 114 } 115 116 if(s1.length() > s2.length()) 117 { 118 Max = s1; 119 Min = s2; 120 } 121 else if (s1.length() == s2.length() && s1[0] > s2[0]) 122 { 123 Max = s1; 124 Min = s2; 125 } 126 else { 127 Min = s1; 128 Max = s2; 129 } 130 Sub(Max, Min); 131 } 132 else 133 Add(); 134 135 return 0; 136 }
大整数加法与减法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。