Home  >  Article  >  Backend Development  >  How to add strings in PHP

How to add strings in PHP

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-07-13 15:47:383765browse

Given two non-negative integers num1 and num2 in string form, calculate their sum. What should we do at this time? Today, the editor will take you through it, and you can refer to it if you need it.

How to add strings in PHP

Given two non-negative integers num1 and num2 in string form, calculate their sum.

Tip:

The length of num1 and num2 are both less than 5100. Both num1 and num2 only contain numbers 0-9. Neither num1 nor num2 contains any leading zeros.

You cannot use any inner When building the BigInteger library, you cannot directly convert the input string into an integer form.

Problem-solving ideas

Add bit by bit, and the remainders are accumulated and judged. Finally it is 0, no more looping

Code

class Solution {
    /** 
    * @param String $num1 
    * @param String $num2 
    * @return String 
    */
    function addStrings($num1, $num2) {
        $cur = 0;
        $i = strlen($num1) - 1;
        $j = strlen($num2) - 1;
        $str = '';
        $carry = 0;
        while ($i >= 0 || $j >= 0 || $carry) {
            $cur = $carry;
            if ($i >= 0) {
                $cur += $num1[$i--];
            }
            if ($j >= 0) {
                $cur += $num2[$j--];
            }
            $carry = floor($cur / 10);   // 向下取整,最后一次 0 的情况就不再循环
            $str = $cur % 10 . $str;     // 累连求余之后的结果, .$str 的操作可以避免反转结果
        }
        return $str;
    }}

Recommended learning:php video tutorial

The above is the detailed content of How to add strings in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:hxd.life. If there is any infringement, please contact admin@php.cn delete