Last active
January 19, 2018 22:25
-
-
Save proofoftom/3db5febe8c27e9dcfb9e99cf82b9e0bc to your computer and use it in GitHub Desktop.
Math helper to find the number of carry operations in an addition operation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * @file Math helper to find the number of carry operations in an addition operation. | |
| */ | |
| class CarryOperations | |
| { | |
| /** | |
| * Counts the number of carry operations when adding two numbers. | |
| * | |
| * @param integer $num1 First number to be added. | |
| * @param integer $num2 Second number to be added. | |
| * | |
| * @return integer Number of carry operations. | |
| */ | |
| public static function count($num1, $num2) | |
| { | |
| // Split the two numbers into columns. | |
| $num1_columns = str_split($num1); | |
| $num2_columns = str_split($num2); | |
| // Set initial amount of carries. | |
| $carries = 0; | |
| // By default there is no previous carry. | |
| $carried = false; | |
| // Since the order is indeterminate, find the number with the most columns. | |
| $amount_of_columns = (strlen($num1) > strlen($num2)) ? strlen($num1) : strlen($num2); | |
| // Loop through each column and determine if the respective column carries. | |
| for ($i = $amount_of_columns; $i > 0 ; $i--) { | |
| $column_sum = array_pop($num1_columns) + array_pop($num2_columns); | |
| // If this column carries, save the carry to apply to the next column. | |
| $carried = _isCarry($column_sum, $carried); | |
| if ($carried) $carries++; | |
| } | |
| return $carries; | |
| } | |
| /** | |
| * Calculate if an added column incures a carry. | |
| * | |
| * @param integer $column_sum The sum of the two columns. | |
| * @param boolean $carried True (1) if the previous column carried. | |
| * | |
| * @return boolean True if this column incures a carry. | |
| */ | |
| private function _isCarry($column_sum, $carried) | |
| { | |
| if ($column_sum + $carried >= 10) { | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| } | |
| } | |
| echo CarryOperations::count(1, 9999); | |
| // Output: 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment