Write a C++ program to divide two integers (dividend and divisor) without using multiplication, division and mod operator
- برمجة سي بلس بلس
- برمجة
- 2021-05-13
- MarwaMohammed
الأجوبة
#include <iostream>
using namespace std;
int divide_result(int dividend_num, int divisor_num) {
if (dividend_num == INT_MIN && divisor_num == -1)
{
return INT_MAX;
}
bool minus = ((dividend_num > 0) ^ (divisor_num > 0));
long long num = labs(dividend_num);
long long div = labs(divisor_num);
int ans = 0;
while (num >= div)
{
long long temp = div;
long long mul = 1;
while(num >= (temp << 1))
{
mul <<= 1;
temp <<= 1;
}
ans += mul;
num -= temp;
}
return minus ? -ans: ans;
}
int main(void)
{
int dividend_num = 7;
int divisor_num = 2;
cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
dividend_num = -17;
divisor_num = 5;
cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
dividend_num = 35;
divisor_num = 7;
cout << "\nDividend " << dividend_num << " Divisor " << divisor_num << endl;
cout << "Result: " << divide_result(dividend_num, divisor_num) << endl;
return 0;
}
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال