zoukankan      html  css  js  c++  java
  • [leetcode]415. Add Strings字符串相加

    Given two non-negative integers 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.

    题目

    如题

    思路

    1. while loop will run as long as there is character left in nums1, nums2 or carry 

    2. from right to left, each character is converted to integer

    3. If the shorter string is exhausted first, the value will be forced to `0` as default

    代码

     1 class Solution {
     2       public String addStrings(String num1, String num2) {
     3         //how many digits will be added? three! 1st from num1Array, 2nd from num2Array, 3rd from carry
     4         int carry = 0;
     5         int num1Len = num1.length()-1;
     6         int num2Len = num2.length()-1;
     7 
     8         // StringBuilder can append and remove, more efficient
     9         StringBuilder sb = new StringBuilder();
    10 
    11         //while loop will run as long as there is character left in nums1, nums2 or carry 
    12         while(num1Len >= 0 || num2Len >=0 || carry >0){
    13             // from right to left, each character is converted to integer
    14             // If the shorter string is exhausted first, the value will be forced to `0` as default
    15             int update1 = num1Len>=0 ? num1.charAt(num1Len--)-'0' :0;
    16             int update2 = num2Len>=0 ? num2.charAt(num2Len--)-'0' :0;
    17             int sum = update1 + update2 + carry;
    18             sb.insert(0,sum%10);
    19             carry = sum/10;
    20         }    
    21         return sb.toString();
    22     }
    23 }
  • 相关阅读:
    MFC 监控界面上所有文本框值的变化
    VC遍历窗体控件的实现
    VC关于置顶窗口的方法小结
    查看linux系统版本命令
    windows下maven打包eclipse工程
    Java多线程-一个简单的线程,实现挂起和恢复的功能
    maven常用操作
    eclipse调试java技巧
    Linux下报 java.net.SocketException权限不够 异常解决
    体验vSphere 6之1-安装VMware ESXi 6 RC版(转载)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9823953.html
Copyright © 2011-2022 走看看