Problem
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
NoticeThe length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Given num1 = "123", num2 = "45"
return "168"
public class Solution { /* * @param num1: a non-negative integers * @param num2: a non-negative integers * @return: return sum of num1 and num2 */ public String addStrings(String num1, String num2) { //start from adding the last digits of num1, num2: //if the current sum > 10, save 1 in `carry`, //add to the front of StringBuilder sb //... doing this till both indice less than 0 int i = num1.length()-1, j = num2.length()-1, carry = 0, curSum = 0; StringBuilder sb = new StringBuilder(); while (i >= 0 || j >= 0 || carry == 1) { //Integer.valueOf(String.valueOf(char)) is to remind me that the value of char is mapped to the decimal value in ascii int curNum1 = i >= 0 ? Integer.valueOf(String.valueOf(num1.charAt(i))) : 0; int curNum2 = j >= 0 ? Integer.valueOf(String.valueOf(num2.charAt(j))) : 0; int sum = carry + curNum1 + curNum2; curSum = sum % 10; carry = sum/10; sb.insert(0, curSum); i--; j--; } return sb.toString(); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/70857.html
Problem Assume you have an array of length n initialized with all 0s and are given k update operations. Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each el...
摘要:又用到了取余公式,推導出。用循環對數組各位進行轉換和相乘和累加。因為第二個取余公式證明乘積取余與乘數相加后再取余等價于乘積取余,所以在每個循環內都進行一次取余,以免乘積太大溢出。 Problem In data structure Hash, hash function is used to convert a string(or any other type) into an int...
Problem Xiao Ming is going to help companies buy fruit. Give a codeList, which is loaded with the fruit he bought. Give a shoppingCart, which is loaded with target fruit. We need to check if the order...
摘要:建立映射整數數組字符串數組,這兩個數組都要從大到小,為了方便之后對整數進行從大到小的分解,以便用從前向后建立數字。建立,存入的數值對應關系。 Problem Integer to RomanGiven an integer, convert it to a roman numeral.The number is guaranteed to be within the range fro...
摘要:這道題有一些細節需要留意。新數會不會溢出符號位如何處理用慣用的做法,除以取余,得到最低位,放進。每次循環乘以累加當前最低位,同時除以不斷減小。要點在于考慮乘累加運算的情況,用分支語句判斷發生溢出的條件。最后的結果要加上之前排除的符號位。 Problem Reverse digits of an integer. Returns 0 when the reversed integer o...
閱讀 4549·2021-09-10 11:22
閱讀 530·2019-08-30 11:17
閱讀 2564·2019-08-30 11:03
閱讀 430·2019-08-29 11:18
閱讀 3455·2019-08-28 17:59
閱讀 3218·2019-08-26 13:40
閱讀 3157·2019-08-26 10:29
閱讀 1137·2019-08-26 10:14