s2.length()){ .._美团优选输入输出">
赞
踩
字符串数字相加,输出字符串。
代码:
- public class Test32 {
- public static void main(String[] args) {
- String s1 = "13";
- String s2 = "212";
-
- int size =0;
- if(s1.length()>s2.length()){
- size = s1.length();
- }else{
- size = s2.length();
- }
-
- String returnStr = "";
- int flage = 0;
- Integer jinWei = 0;
- while(flage<size||jinWei>0){
- //计算C1
- int intC1 = 0;
- int indexS1 = s1.length()-flage-1;
- if(indexS1>=0){
- Character c1 = s1.charAt(indexS1);
- intC1 = c1 - '0';
- }
- //计算C2
- int intC2 = 0;
- int indexS2 = s2.length()-flage-1;
- if(indexS2 >=0){
- Character c2 = s2.charAt(indexS2);
- intC2 = c2 - '0';
- }
- //C1,C2相加
- int weiC = intC1+intC2+jinWei;
- //判断是否超10,进位。
- if(weiC>=10){
- jinWei = 1;
- weiC = 10 -weiC;
- }
- //前缀垒数
- returnStr = weiC + returnStr;
- //移动指针
- flage++;
- }
-
- System.out.println(returnStr);
- }
- }
输出结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。