Skip to content

Latest commit

 

History

History
119 lines (101 loc) · 2.98 KB

415.add-strings.md

File metadata and controls

119 lines (101 loc) · 2.98 KB

字符串相加

题目

思路

字符串相加, 可将字符串进行反转, 而后从两个数组的第一位开始运算, 以及判断是否进位.

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var addStrings = function(num1, num2) {
  const num1Length = num1.length
  const num2Length = num2.length
  const maxLength = num1Length > num2Length ? num1Length : num2Length
  const num1Arr = num1.split('')
  const num2Arr = num2.split('')
  /** 数组反转. 之后好操作 */
  num1Arr.reverse()
  num2Arr.reverse()
  /** 进位 */
  let carry = false
  let results = []
  for (let i = 0; i < maxLength; i++) {
    const tmp = Number(num1Arr[i] || 0) + Number(num2Arr[i] || 0) + (carry ? 1 : 0)
    carry = tmp > 9
    /** 直接将值传到数组头部. 省去反转操作 */
    results.unshift(carry ? tmp - 10 + '' : tmp + '')
  }
  if (carry) {
    /** 进位符号如果还存在, 还得推送个1进来 */
    results.unshift('1')
  }
  return results.join('')
};
class Solution {
  /**
   * @param String $num1
   * @param String $num2
   * @return String
   */
  function addStrings($num1, $num2) {
    $num1Arr = str_split($num1);
    $num2Arr = str_split($num2);
    $num1Length= count($num1Arr);
    $num2Length = count($num2Arr);
    $maxLength = $num1Length > $num2Length ? $num1Length : $num2Length;
    $num1Arr = array_reverse($num1Arr);
    $num2Arr = array_reverse($num2Arr);

    $carry = false;
    $results = [];

    for ($i = 0; $i < $maxLength; $i++) {
      $tmp = (int)$num1Arr[$i] + (int)$num2Arr[$i] + ($carry ? 1 : 0);
      $carry = $tmp > 9;

      array_unshift($results, $carry ? $tmp - 10 : $tmp);
    }

    if ($carry) {
      array_unshift($results, 1);
    }

    $result = "";
    $resultCount = count($results);
    for ($i = $resultCount; $i >= 0; $i--) {
      $result = strval($results[$i]).$result;
    }

    return $result;
  }
}
class Solution {
  public String addStrings(String num1, String num2) {
    ArrayList<Integer> num1Arr = reverse(num1.split(""));
    ArrayList<Integer> num2Arr = reverse(num2.split(""));
    int num1Length = num1Arr.size();
    int num2Length = num2Arr.size();
    int maxLength = num1Length > num2Length ? num1Length : num2Length;
    boolean carry = false;
    // String result = "";
    StringBuilder result = new StringBuilder();
    // num1Arr.re

    for (int i = 0; i < maxLength; i++) {
      int tmp = (i >= num1Length ? 0 : num1Arr.get(i)) + (i >= num2Length ? 0 : num2Arr.get(i)) + (carry ? 1 : 0);

      carry = tmp > 9;
      result.append(carry ? tmp - 10 : tmp);
    }

    if (carry) {
      result.append('1');
    }

    return result.reverse().toString();
  }

  public ArrayList<Integer> reverse (String[] arr) {
    ArrayList<Integer> results = new ArrayList<Integer>();
    int length = arr.length;

    for (int i = length - 1; i > -1; i--) {
      results.add(Integer.parseInt(arr[i]));
    }
    return results;
  }
}