Code For Fun

PHP – Sum of 2 big integer
function sumBigInteger($a, $b){
    $aArray = array_reverse(str_split($a));
    $bArray = array_reverse(str_split($b));
    if(count($bArray) > count($aArray)){
        $tmpArray = $aArray;
        $aArray = $bArray;
        $bArray = $tmpArray;
    }
    $sum = [];
    foreach($aArray as $aIndex => $aValue){
        $bValue = 0;
        if(isset($bArray[$aIndex]))
            $bValue = $bArray[$aIndex];

        if(!isset($sum[$aIndex])) $sum[$aIndex] = 0;

        $sum[$aIndex] = $sum[$aIndex] + $aValue + $bValue;

        if($sum[$aIndex] > 9 ){
            $sum[$aIndex+1] = intdiv($sum[$aIndex],10) ;
            $sum[$aIndex] = $sum[$aIndex]%10;
            
        }
        //print_r($sum);
    }
    return implode("", array_reverse($sum));
}
CategoriesUncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *