"I am trying to divide a integer by bit manipultion and return the quotient. I tried by debugging.At first debugging statement nothing is printed and at second second statement quotient is zero."
#include <iostream>
using namespace std;
//function with input arguments a as dividend and b as divisor
int divide(int A, int B) {
if(A==0)return 0;
int sign = ((A < 0) ^ (B < 0)) ? -1 : 1;
// remove sign of operands
long long a= abs(A);
long long b= abs(B);
// Initialize the quotient
long long quotient = 0, temp = 0;
// test down from the highest bit and
// accumulate the tentative value for
// valid bit
for (int i = 31; i >= 0; --i) {
if (temp + (b << i) <= a) {
//temp stores the the mutiplier of divisor if it is less than or equal to //dividend
temp += b<< i;
//updates the quotient
quotient |= 1LL << i;
cout<<quotient;
}
}cout<<quotient;
return (int)(sign*quotient);
}
int main() {divide(-2147483648,-1);
}
//Expected=2147483647.
//Actual =0
Aucun commentaire:
Enregistrer un commentaire