NowCoder001–大数加法
题目描述
以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
(字符串长度不大于100000,保证字符串仅由’0’~'9’这10种字符组成)
示例1
输入
"1","99"
返回值
"100"
说明
1+99=100
代码:
package com.xujinshan.nowcoder.nc001;
/**
* @Author: xujinshan361@163.com
* NowCoder001--大数加法
* 题目描述
* 以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
* (字符串长度不大于100000,保证字符串仅由'0'~'9'这10种字符组成)
* 示例1
* 输入
*
* "1","99"
*
* 返回值
*
* "100"
*
* 说明
*
* 1+99=100
*/
class Solution{
public String solve(String s,String t){
int sLength = s.length(); // 获取字符串s长度
int tLength = t.length(); // 获取字符串t长度
int m =sLength>tLength?tLength:sLength; // 将m设置成短的那个字符串,先进行操作
char[] sChar = s.toCharArray(); // 将字符串变成字符数组
char[] tChar = t.toCharArray();
char c = '0'; // 字符0 为了获取字符对应的数字的操作
int index = 0; // 保存进位结果
StringBuilder sb = new StringBuilder(); // StringBuilder 保存结果集
for (int i = 0; i < m; i++) { // 从字符数组的后面开始往前加,先进行m位的加法
int res = (sChar[sLength-i-1] -c)+ (tChar[tLength-i-1]-c) +index;
sb.append(res%10);
index= res/10;
}
// 加多余出来的
if(sLength>tLength){
for (int i = 0; i < sLength - m; i++) {
int res = (sChar[sLength-i-m-1] -c) +index;
sb.append(res%10);
index= res/10;
}
}
if(sLength<=tLength){
for (int i = 0; i < tLength - m; i++) {
int res = (tChar[tLength-i-m-1]-c) +index;
sb.append(res%10);
index= res/10;
}
}
// 看最后一位是否有进位
if(index>0){
sb.append(index);
}
// 返回结果之前需要翻转一次
return sb.reverse().toString();
}
}
public class NowCoder001 {
public static void main(String[] args) {
System.out.println(new Solution().solve("1","99"));
}
}