MCPcopy Index your code
hub / github.com/careercup/ctci / divide

Method divide

java/Chapter 7/Question7_4/Question.java:45–64  ·  view source on GitHub ↗
(int a, int b)

Source from the content-addressed store, hash-verified

43 /* Divide a by b by literally counting how many times b can go into
44 * a. That is, count how many times you can add b to itself until you reach a. */
45 public static int divide(int a, int b) throws java.lang.ArithmeticException {
46 if (b == 0) {
47 throw new java.lang.ArithmeticException("ERROR: Divide by zero.");
48 }
49 int absa = abs(a);
50 int absb = abs(b);
51
52 int product = 0;
53 int x = 0;
54 while (product + absb <= absa) { /* don't go past a */
55 product += absb;
56 x++;
57 }
58
59 if ((a < 0 && b < 0) || (a > 0 && b > 0)) {
60 return x;
61 } else {
62 return negate(x);
63 }
64 }
65
66 public static int randomInt(int n) {
67 return (int) (Math.random() * n);

Callers 1

mainMethod · 0.95

Calls 2

absMethod · 0.95
negateMethod · 0.95

Tested by

no test coverage detected