Write a C# program to divide two given integers (dividend and divisor) and get the quotient without using multiplication, division and mod operator
- برمجة سي شارب
- برمجة
- 2021-05-31
- ahmadghneem
الأجوبة
using System;
using System.Text;
namespace exercises {
class Program {
static void Main(string[] args) {
int dividend, divisor;
dividend = 7;
divisor = 3;
if (divisor > 0) {
Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
Console.WriteLine("Quotient= " + Divide(dividend, divisor));
}
dividend = -17;
divisor = 5;
if (divisor > 0) {
Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
Console.WriteLine("Quotient= " + Divide(dividend, divisor));
}
dividend = 35;
divisor = 7;
if (divisor > 0) {
Console.WriteLine("Dividend = " + dividend + ", Divisor = " + divisor);
Console.WriteLine("Quotient= " + Divide(dividend, divisor));
}
}
public static int Divide(int dividend, int divisor) {
uint x = dividend > 0 ? (uint) dividend : (uint) - dividend;
uint y = divisor > 0 ? (uint) divisor : (uint) - divisor;
uint result = 0, z = 0;
var idx = 0;
while (x >= y) {
z = y;
for (idx = 0; x >= z && z != 0; idx++, z *= 2) {
x -= z;
result += (uint) 1 << idx;
}
}
return (dividend ^ divisor) >> 31 == -1 ?
(int) - result :
result > int.MaxValue ? int.MaxValue : (int) result;
}
}
}
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال