From ba6c83fca9575412bfbf53edcb3e5fc190ced4a8 Mon Sep 17 00:00:00 2001 From: Ivan Date: Thu, 27 Jul 2017 23:58:16 +0800 Subject: [PATCH] proposed solution for add 2 integers with max bit length --- math_probability/sum_two/sum_two_solution.ipynb | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/math_probability/sum_two/sum_two_solution.ipynb b/math_probability/sum_two/sum_two_solution.ipynb index cfba2a3..62bfcaf 100644 --- a/math_probability/sum_two/sum_two_solution.ipynb +++ b/math_probability/sum_two/sum_two_solution.ipynb @@ -122,11 +122,14 @@ " def sum_two(self, a, b):\n", " if a is None or b is None:\n", " raise TypeError('a or b cannot be None')\n", - " result = a ^ b;\n", - " carry = (a&b) << 1\n", - " if carry != 0:\n", - " return self.sum_two(result, carry)\n", - " return result;" + " #max bit length, change to 32 for 32bit\n", + " max_positive = 2 ** 64\n", + " min_negative = -2 ** 64\n", + " while b != 0:\n", + " if b == max_positive:\n", + " return a ^ min_negative\n", + " a,b = a ^ b,(a&b)<<1\n", + " return a" ] }, {