zoukankan      html  css  js  c++  java
  • 415. Add Strings(LeetCode)

    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 class Solution {
       2 public:
       3     string addStrings(string num1, string num2) {
       4         if (num1.size() < num2.size()) return addStrings(num2, num1);
       5         int extra = 0;
       6         int idx1 = num1.size() - 1;
       7         int idx2 = num2.size() - 1;
       8         while (idx1 >= 0) {
       9             int sum = extra + num1[idx1] - '0';
      10             if (idx2 >= 0)
      11                 sum = sum + num2[idx2] - '0';
      12             num1[idx1] = '0' + sum % 10;
      13             extra = sum / 10;
      14             idx1--;
      15             idx2--;
      16         }
      17         if (extra) num1 = "1" + num1;
      18         return num1;
      19     }
      20 };
  • 相关阅读:
    开发管理工具(日常)
    python之uWSGI和WSGI
    php之Opcache
    nginx之健康检查
    重构糟糕的代码(一)
    PHP之50个开源项目
    Redis之各版本特性
    Redis之淘汰策略
    Redis之过期策略
    高并发之nginx限制
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6874351.html
Copyright © 2011-2022 走看看