两数相加

滴滴面试二轮挂

评语:技术可以,算法不行。

面试官说给你出个简单的吧:两个大数相加

说实话我之前做过,我忘记了,马赛网不能调试,所以只能手撕,当然会部分代码出错,提示了三次才写下来

评语:


不要着急编码

理清思路以及合理性

代码

package com.yang.leetcode.exam;

import java.util.Arrays;

/**
 * @author: fudy
 * @date: 2021/04/17 下午 03:26
 * @Decription:
 **/
public class Main {
    public static void main(String[] args) {

        // 将数值转为string
        long a = 3512345678L;
        long b = 98776344324244L;
        System.out.println(a+b);
        String arg1 = String.valueOf(a);
        String arg2 = String.valueOf(b);
        // 设定结果值
        StringBuffer sb = new StringBuffer(Math.max(arg1.length(),arg2.length()));
        // 将低位的进位储存起来
        int temp = 0;
        // 如果其中一个数结束了,结束循环
        int arg1Index = arg1.length()-1;
        int arg2Index = arg2.length()-1;
        while(arg1Index>=0 || arg2Index >=0){
            // 遍历两个数进行低位相加
            if (arg1Index < 0 || arg2Index < 0){
                if (arg1Index > arg2Index){
                    sb.append(arg1.charAt(arg1Index));
                    --arg1Index;
                }else {
                    sb.append(arg2.charAt(arg2Index));
                    --arg2Index;
                }
                continue;
            }
            int a1 = Integer.parseInt(arg1.charAt(arg1Index)+"");
            int b2 = Integer.parseInt(arg2.charAt(arg2Index)+"");
            int resultTemp = a1+b2;
            int result2 = resultTemp%10+temp;
            sb.append(result2);
            temp = resultTemp/10;
            --arg1Index;
            --arg2Index;
        }
        // 补充较长数组位
        //打印相加值
        System.out.println(sb.reverse().toString());
    }


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值