算数运算的模拟相关问题
大数的运算,不用乘除做除法,等等。待补充。。。
01 模拟两个大数相乘
#include<iostream> #include<vector> using namespace std; /*01 模拟两个大数相乘*/ string multiply(string str1, string str2) { vector<int> vec(str1.size() + str2.size(), 0); for (int i = 0; i < str1.size(); i++) { for (int j = 0; j < str2.size(); j++) { vec[i + j + 1] += (str1[i] - '0')*(str2[j] - '0'); } } int tmp = 0; for (auto it = vec.rbegin(); it != vec.rend(); it++) { *it += tmp; tmp = *it / 10; *it %= 10; } string res; if (vec[0] != 0) { res.push_back(vec[0] + '0'); } for (int i = 1; i < vec.size(); i++) { res.push_back(vec[i] + '0'); } return res; }
02. 不用乘除做除法
借鉴思路如下:
”Suppose we want to divide 15 by 3, so 15 is dividend and 3 is divisor. Well, division simply requires us to find how many times we can subtract the divisor from the the dividend without making the dividend negative.
Let's get started. We subtract 3 from 15 and we get 12, which is positive. Let's try to subtract more. Well, we shift 3 to the left by 1 bit and we get 6. Subtracting 6 from 15 still gives a positive result. Well, we shift again and get 12. We subtract 12 from 15 and it is still positive. We shift again, obtaining 24 and we know we can at most subtract 12. Well, since 12 is obtained by shifting 3 to left twice, we know it is 4times of 3. How do we obtain this 4? Well, we start from 1 and shift it to left twice at the same time. We add 4 to an answer (initialized to be 0). In fact, the above process is like 15 = 3 * 4 + 3. We now get part of the quotient (4), with a remainder 3.
Then we repeat the above process again. We subtract divisor = 3 from the remaining dividend = 3 and obtain 0. We know we are done. No shift happens, so we simply add 1 << 0 to the answer.“
int divide(int divided, int divider) { /*需要格外注意两个会溢出的条件判断*/ if (divider == 0 || (divided == INT_MIN&÷r == -1)) return INT_MAX; int res = 0; bool sign = false; if ((divided < 0 && divider>0) || (divided > 0 && divider < 0)) sign = true; long long ded = labs(divided), der = labs(divider); while (ded >= der) { long long tmpder = der; int tmpres = 1; while (ded >= (tmpder << 1)) { tmpder <<= 1; tmpres <<= 1; } res += tmpres; ded -= tmpder; } return sign ? -res : res; }
测试代码:
int main() { string str1 = "1234567"; string str2 = "99"; string res = multiply(str1,str2); int ded = atoi(str1.c_str()), der = atoi(str2.c_str()); int res2 = divide(ded, der); return 0; }