实现两个大数相加(php和golang版本)

21 篇文章 1 订阅

两个大数相加是常见的面试题,无论是PHP开发,还是golang开发,都是如此。下面分别给出两个大数相加PHP版本和golang版本的实现方案,给有需要的同学提供借鉴,希望对大家有所帮助。

一、PHP语言版本

/**
     * add
     * a,b should be numeric
     * @param $a string
     * @param $b string
     * @return string
     */
    function add($a, $b)
    {
        $lenA = strlen($a);
        $lenB = strlen($b);

        $j = 0; //进位数
        $re = '';
        for ($inxA = $lenA - 1, $inxB = $lenB - 1; ($inxA >= 0 || $inxB >= 0); --$inxA, --$inxB) {
            $itemA = ($inxA >= 0) ? (int)$a[$inxA] : 0;
            $itemB = ($inxB >= 0) ? (int)$b[$inxB] : 0;
            $sum = $itemA + $itemB + $j;
            if ($sum > 9) {
                $j = 1;
                $sum = $sum - 10;
            } else {
                $j = 0;
            }
            $re = (string)$sum . $re;
        }
        if ($j > 0) {
            $re = (string)$j . $re;
        }

        return $re;
    }

在使用的时候,直接调用该方法即可。

 

二、golang版本

package main

import (
	"strings"
	"os"
	"bufio"
	"fmt"
	"strconv"
)

func bigDataAdd(strA, strB string) (result string) {
	lenA := len(strA)
	lenB := len(strB)
	lenBase := 0
	if lenA > lenB {
		lenBase = lenA
	} else {
		lenBase = lenB
	}

	j := 0 //进位数
	result = ""
	inxA := lenA - 1
	inxB := lenB - 1
	itemA := 0
	itemB := 0
	for inxBase := lenBase - 1; inxBase >= 0 ; inxBase-- {
		itemA = 0
		if inxA >= 0 {
			itemA, _ = strconv.Atoi(string(strA[inxA]))
			inxA--
		}
		itemB = 0
		if inxB >= 0 {
			itemB, _ = strconv.Atoi(string(strB[inxB]))
			inxB--
		}
		sum := itemA + itemB + j
		if sum > 9 {
			j = 1
			sum = sum - 10
		} else {
			j = 0
		}
		result = strconv.Itoa(sum) + result;
	}

	if j > 0 {
		result = strconv.Itoa(j) + result;
	}

	return
}

func main() {
	fmt.Println("Input a+b:")
	reader := bufio.NewReader(os.Stdin)
	result, _, err := reader.ReadLine()
	if err != nil {
		fmt.Printf("read from console error: %v", err)
	}

	strSlice := strings.Split(string(result), "+")
	if len(strSlice) != 2 {
		fmt.Println("Please input  a+b")
	}
	strNum1 := strings.TrimSpace(strSlice[0])
	strNum2 := strings.TrimSpace(strSlice[1])
	resMultiply := bigDataAdd(strNum1, strNum2)
	fmt.Printf("add result = %s\n", resMultiply)
}

执行结果如下所示:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值