2 条题解
-
0
这是一坨屎山的字符串解法,回头会完善出来有注释的版本,先传上来orz
import java.util.Scanner; public class P566 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String num1 = sc.nextLine(); String num2 = sc.nextLine(); boolean positiveNum1 = num1.charAt(0) != '-'; boolean positiveNum2 = num2.charAt(0) != '-'; num1 = RemoveSymbol(num1,positiveNum1); num2 = RemoveSymbol(num2,positiveNum2); if(num1.length() > num2.length()) { int count = num1.length() - num2.length(); for(int i = 0;i < count;i++) { num2 = "0" + num2; } } else if (num1.length() < num2.length()) { int count = num2.length() - num1.length(); for(int i = 0;i < count;i++) { num1 = "0" + num1; } } String aws = ""; if(positiveNum1 ^ positiveNum2){ aws = SubtractionOperation(num1,num2,positiveNum1); }else { aws = AdditionOperation(num1,num2); if(!positiveNum1 && aws.charAt(0)!='0'){ aws = "-"+aws; } } if(aws.isEmpty()) { aws = "0"; } System.out.println(aws); } public static String RemoveSymbol(String num,boolean positiveNum){ if(!positiveNum){ num = num.substring(1); } return num; } public static String AdditionOperation(String num1,String num2){ String aws = ""; boolean judge = false; for(int i = num1.length()-1;i >= 0;i--) { int a = num1.charAt(i)-48; int b = num2.charAt(i)-48; int sum = a + b; if(judge) { sum++; judge = false; } if(sum >= 10) { sum = sum%10; judge = true; } aws = sum + aws; if(i == 0 && judge) { aws = "1" + aws; } } return aws; } public static String SubtractionOperation(String num1,String num2,boolean positiveNum1){ String aws = ""; String temp; if(!positiveNum1){ temp = num1; num1 = num2; num2 = temp; } boolean judge = false; boolean isNegative = false; for(int i = num1.length()-1;i >= 0;i--) { int a = num1.charAt(i)-48; int b = num2.charAt(i)-48; int sub = a - b; if(judge) { sub--; judge = false; } if(sub < 0) { boolean isEnd = true; for (int j = i - 1; j >= 0 ; j--) { if(num1.charAt(j) != '0'){ isEnd = false; break; } } if(isEnd){ sub = -sub; if(i == 0){ judge = true; } }else { sub += 10; judge = true; } } aws = sub + aws; if(i == 0 && judge) { isNegative = true; } } aws = RemoveExtraZero(aws); if(isNegative){ aws = "-"+aws; } return aws; } public static String RemoveExtraZero(String aws){ String aws2 = ""; boolean judge2 = true; for(int i = 0;i < aws.length();i++) { if(aws.charAt(i) == '0' && judge2) { continue; } else if(aws.charAt(i) != '0') { judge2 = false; } aws2 += aws.charAt(i); } return aws2; }
- 1
信息
- ID
- 566
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 3
- 标签
- 递交数
- 282
- 已通过
- 35
- 上传者