[Amazon] Big Integer Addition
来源:互联网 发布:java大牛的博客 编辑:程序博客网 时间:2024/06/05 06:18
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Notice
- The 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
Example
Given num1 = "123"
, num2 = "45"
return "168"
思路:把长度短的字符串用0补齐位数,从最后一位开始借位相加,反转即可。
分析:"123"和"045"
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) { StringBuffer sb=new StringBuffer(); int len=Math.max(num1.length(),num2.length()); int carry=0; for(int i=len-1;i>=0;i--){ if(num1.length()<num2.length()){ for(int j=num1.length();j<num2.length();j++){ num1="0"+num1; } } if(num1.length()>num2.length()){ for(int j=num2.length();j<num1.length();j++){ num2="0"+num2; } } char c1=num1.charAt(i); char c2=num2.charAt(i); int digit=(carry+(c1-'0')+(c2-'0'))%10; sb.append(digit); carry=(carry+(c1-'0')+(c2-'0'))/10; } if(carry!=0){ sb.append(carry); } return sb.reverse().toString(); }}
第二遍
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) { int diff=Math.abs(num1.length()-num2.length()); if(num1.length()>num2.length()){ for(int i=0;i<diff;i++){ num2="0"+num2; } }else{ for(int i=0;i<diff;i++){ num1="0"+num1; } } String result=""; int carry=0; for(int i=num1.length()-1;i>=0;i--){ int sum=carry+(num1.charAt(i)-'0')+(num2.charAt(i)-'0'); //要注意charAt之后要-'0' int digit=sum%10; result+=digit; carry=sum/10; } if(carry!=0){ result+=carry; } return new StringBuffer(result).reverse().toString(); }}
阅读全文
0 0
- [Amazon] Big Integer Addition
- Big Integer Addition
- Big Integer Addition
- Big Integer Addition
- LintCode :Big Integer Addition
- lintcode(655)Big Integer Addition
- Google/LintCode:E-Big Integer Addition
- LintCode python 小白4-Big Integer Addition
- Big Integer Addition存储在字符串内的整数相加
- Sicily 1020 Big Integer
- sicily 1020 Big Integer
- 1020. Big Integer
- Sicily.1020. Big Integer
- Sicily 1020. Big Integer
- sicily 1020. Big Integer
- Sicily 1020. Big Integer
- Sicily 1020 Big Integer
- sicily 1020.Big Integer
- 从零开始编写深度学习库(五)PoolingLayer 网络层CPU编写
- Android中的onActivityResult和setResult方法的使用
- 04.24 网络相关命令配置实践
- python中enumerate函数用法
- python小程序-0014
- [Amazon] Big Integer Addition
- 设计模式-创建型模式
- BS结构分层优势以及缺陷
- Hive 1.2.1000.2.5.3.0-37 跑join语句报错
- django 1.11 自定义分页功能的实现
- 浏览器兼容问题
- SVN服务器搭建之提交日志模版构建
- Matlab 报错 Error java.lang.OutOfMemoryError: GC overhead limit exceeded 解决
- java多线程模拟售票