zoukankan      html  css  js  c++  java
  • leetcode415---字符串大数相加

    Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

    Note:

    1. The length of both num1 and num2 is < 5100.
    2. Both num1 and num2 contains only digits 0-9.
    3. Both num1 and num2 does not contain any leading zero.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

    我的第一个想法就是选好两个字符串,然后模拟加法进位,然后用一个字符串接着,同时记住进位,最后返回这个字符串的反转即可。

    没有想到什么比较好的解决思路

    public class Solution {
        public String addStrings(String num1, String num2) {
            StringBuilder sb = new StringBuilder();
            int carry = 0;
            for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--){
                int x = i < 0 ? 0 : num1.charAt(i) - '0';
                int y = j < 0 ? 0 : num2.charAt(j) - '0';
                sb.append((x + y + carry) % 10);
                carry = (x + y + carry) / 10;
            }
            if(carry != 0)
                sb.append(carry);
            return sb.reverse().toString();
        }
    }
  • 相关阅读:
    java包和jar包
    java异常总结
    java异常练习2
    java中的异常处理机制_函数覆盖时的异常特点
    React(三)TableBar,ToDoList,Redux案例
    React(二)组件通信
    React(二)组件通信
    React(一)起步
    React(一)起步
    Vue(二)进阶
  • 原文地址:https://www.cnblogs.com/linkstar/p/5998891.html
Copyright © 2011-2022 走看看