两个大数相加是常见的面试题,无论是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 = %sn", resMultiply)

}

执行结果如下所示:

efeb657ad85485689e292925384841b8.png

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐