function IncrementBigNum($bigNumString) { $lastIndex = strlen($bigNumString) - 1; if ($bigNumString[$lastIndex] != 9) { $numberToIncrement = CharToInt($bigNumString[$lastIndex]); ++$numberToIncrement; $bigNumString[$lastIndex] = IntToChar($numberToIncrement); } else { if (CheckForAllNines($bigNumString)) { for ($r = 0; $r < $lastIndex + 1; $r++) { $bigNumString[$r] = "0"; } $bigNumString = "1" . $bigNumString; } else { $indexFirstNonNine = GetFirstNonNine($bigNumString); $numberToIncrement = CharToInt($bigNumString[$indexFirstNonNine]); ++$numberToIncrement; $bigNumString[$indexFirstNonNine] = IntToChar($numberToIncrement); for ($d = $indexFirstNonNine + 1; $d < $lastIndex + 1; $d++) { $bigNumString[$d] = "0"; } } } echo "Result: " . $bigNumString . "\n"; }
/** * This function takes a string representing a large number, * increments it by 1, and returns the result * * @param array $bigNumString A string representation of a large number * * @return array $bigNumString large number string after increment */ function IncrementBigNum($bigNumString) { //Get the last index of the string $lastIndex = strlen($bigNumString) - 1; //Simply increment the last number if it is not nine if ($bigNumString[$lastIndex] != 9) { //Convert last number to an integer to allow increment $numberToIncrement = CharToInt($bigNumString[$lastIndex]); ++$numberToIncrement; //Revert integer to a char and replace in string/array $bigNumString[$lastIndex] = IntToChar($numberToIncrement); } else { if (CheckForAllNines($bigNumString)) { //Set all numbers in large number string to zero for ($r = 0; $r < $lastIndex + 1; $r++) { $bigNumString[$r] = "0"; } //Prepend a one to large number string (eg. "999" becomes "1000") $bigNumString = "1" . $bigNumString; } else { //Find the first non-nine number in the large string $indexFirstNonNine = GetFirstNonNine($bigNumString); //Increment the number $numberToIncrement = CharToInt($bigNumString[$indexFirstNonNine]); ++$numberToIncrement; //Replace the number incremented number in the large number string $bigNumString[$indexFirstNonNine] = IntToChar($numberToIncrement); //Set everything left of incremented number to zero for ($d = $indexFirstNonNine + 1; $d < $lastIndex + 1; $d++) { $bigNumString[$d] = "0"; } } } //Return large number string after performing arithmetic return $bigNumString; }