NowCoder001--大数加法

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"));
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值