How to add strings in PHP

醉折花枝作酒筹
Release: 2023-03-11 13:48:01
forward
3760 people have browsed it

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;
    }}
Copy after login

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!

Related labels:
php
source:hxd.life
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template