题解 | #高精度整数加法#

高精度整数加法

https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

//add函数从后往前挨个处理字符串字符,设置进位变量c记录进位。
//对于多出的部分的字符串,再递归调用一次add函数与进位相加。
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s1 = in.nextLine();
            String s2 = in.nextLine();
            String out = "";
            out = add(s1, s2);
            System.out.print(out);
        }
    }
    public static String add(String s1,String s2){
        int c = 0; //进位
        String out = "";
            int index1 = s1.length()-1;
            int index2 = s2.length()-1;
            while(index1 >= 0 && index2 >= 0){
                int t = Integer.parseInt(s1.charAt(index1)+"")+Integer.parseInt(s2.charAt(index2)+"") + c;
                if(t<10){
                    out = t + out;
                    c = 0;
                }else{
                    out = (t-10) + out;
                    c = 1;
                }
                index1--;index2--;
            }
            
            if(index1 == -1 && index2 == -1){
                if(c == 1){
                    out = c + out;
                }
            }
            else if(index1 == -1 && index2 != -1){
                if(c == 0){
                    out = s2.substring(0,index2+1) + out;
                }else if(c == 1){
                    out = add(s2.substring(0,index2+1), "1") + out;
                }
            }else if(index2 == -1 && index1 != -1){
                if(c == 0){
                    out = s1.substring(0,index1+1) + out;
                }else if(c == 1){
                    out = add(s1.substring(0,index1+1), "1") + out;
                }
            }
        return out;
            
    }
}

全部评论
我好久没刷题了
点赞 回复 分享
发布于 2022-10-18 21:13 山西

相关推荐

05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务