Skip to content

Latest commit

 

History

History
90 lines (74 loc) · 1.78 KB

415.字符串相加.md

File metadata and controls

90 lines (74 loc) · 1.78 KB

415. 字符串相加

url

题目

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

方法

code

js

let addStrings = (num1, num2) => {
    let res = ''
    let carry = 0, i = num1.length - 1, j = num2.length - 1
    while (carry === 1 || i >= 0 || j >= 0) {
        let x = i < 0 ? 0 : num1[i--] - '0'
        let y = j < 0 ? 0 : num2[j--] - '0'
        res += Math.floor((x + y + carry) % 10)
        carry = Math.floor((x + y + carry) / 10)
    }
    return res.split("").reverse().toString()
}

console.log(addStrings('123', '123'))

go

func addStrings(num1 string, num2 string) string {
	reverseStr := func (s string) string {
		runes := []rune(s)
		i, j := 0, len(runes) - 1
		for i < j {
		runes[i], runes[j] = runes[j], runes[i]
		i++
		j--
	}
		return string(runes)
	}
	x := 0
	y := 0
	carry := 0
	i, j := len(num1) - 1, len(num2) - 1
	var res string
	for carry == 1 || i >= 0 || j >= 0 {
		if i < 0 {
			x = 0
		} else {
			x, _ = strconv.Atoi(string(num1[i]))
		}
		if j < 0 {
			y = 0
		} else {
			y, _ = strconv.Atoi(string(num2[j]))
		}
		res += strconv.Itoa((x + y + carry) % 10)
		carry = (x + y + carry) / 10
		i--
		j--
	}
	return reverseStr(res)
}

java

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder str = new StringBuilder();
        int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
        while (carry == 1 || i >= 0 || j >= 0) {
            int x = i < 0 ? 0 : num1.charAt(i--) - '0';
            int y = j < 0 ? 0 : num2.charAt(j--) - '0';
            str.append((x + y + carry) % 10);
            carry = (x + y + carry) / 10; 
        }
        return str.reverse().toString();
    }
}