Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 16, 2013 00:19
Show Gist options
  • Save zhoutuo/4964739 to your computer and use it in GitHub Desktop.
Save zhoutuo/4964739 to your computer and use it in GitHub Desktop.
Divide two integers without using multiplication, division and mod operator.
//
// main.cpp
// Divide_Two_Integers
//
// Created by Zhoutuo Yang on 2/15/13.
// Copyright (c) 2013 Zhoutuo Yang. All rights reserved.
//
#include <iostream>
using namespace std;
int divide(int dividend, int divisor) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
long tempDividend = abs((long)dividend);
long tempDivisor = abs((long)divisor);
if(tempDivisor > tempDividend) {
return 0;
}
int sign = (dividend > 0) xor (divisor > 0) ? -1 : 1;
if(tempDivisor == tempDividend) {
return sign;
}
long quotient = 1;
while(tempDividend >= tempDivisor) {
quotient <<= 1;
tempDivisor <<= 1;
}
quotient >>= 1;
tempDivisor >>= 1;
if(divisor > 0) {
quotient += divide(tempDividend - tempDivisor, divisor);
} else {
quotient -= divide(tempDividend - tempDivisor, divisor);
}
return (int)(quotient * sign);
}
int main(int argc, const char * argv[])
{
cout << divide(2147483647, 1) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment