1947 - 高精度减法4
题目描述
做减法
输入
输入:两个整数a,b(a,b均为长度不超过300位的整数,注意输入的整数可能是负数)
输出
输出:一个整数,表示两数的差(从个位开始,每隔三位加一个" ," 号)。
样例
输入复制
7777777 -29
输出复制
7,777,806
说明
注意负数
来源
高精度算法
标签
高精度算法
(不要出现“请输入:”之类的)
1947 - 高精度减法4
题目描述
做减法
输入
输入:两个整数a,b(a,b均为长度不超过300位的整数,注意输入的整数可能是负数)
输出
输出:一个整数,表示两数的差(从个位开始,每隔三位加一个" ," 号)。
样例
输入复制
7777777 -29
输出复制
7,777,806
说明
注意负数
来源
高精度算法
标签
高精度算法
(不要出现“请输入:”之类的)
关注让 “紫雾凌寒” 来帮你回答,本回答结合 DeepSeek
如果还有问题,请评论或点击头像私信,如果有帮助到您, 请关注、采纳、点赞
下面是具体的代码实现:
import java.util.Scanner;
public class HighPrecisionSubtraction {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
String result = subtract(a, b);
System.out.println(result);
}
public static String subtract(String a, String b) {
boolean negative = false;
if (a.charAt(0) == '-' && b.charAt(0) != '-') {
negative = true;
String temp = a;
a = b;
b = temp;
} else if (a.charAt(0) != '-' && b.charAt(0) == '-') {
negative = false;
b = b.substring(1);
} else if (a.charAt(0) == '-' && b.charAt(0) == '-') {
negative = false;
a = a.substring(1);
b = b.substring(1);
String temp = a;
a = b;
b = temp;
}
StringBuilder result = new StringBuilder();
int carry = 0;
int i = a.length() - 1, j = b.length() - 1;
while (i >= 0 || j >= 0) {
int x = i >= 0? a.charAt(i--) - '0' : 0;
int y = j >= 0? b.charAt(j--) - '0' : 0;
int num = x - y - carry;
if (num < 0) {
num += 10;
carry = 1;
} else {
carry = 0;
}
result.insert(0, num);
}
while (result.length() > 1 && result.charAt(0) == '0') {
result.deleteCharAt(0);
}
for (int k = result.length() - 1, count = 0; k >= 0; k--) {
if (count % 3 == 0 && count > 0) {
result.insert(k, ',');
}
count++;
}
if (negative) {
result.insert(0, '-');
}
return result.toString();
}
}
上述代码是用Java实现的,其他编程语言如Python也可以实现类似功能,核心思路是一致的,只是语法有所不同。例如Python实现如下:
a = input()
b = input()
def subtract(a, b):
negative = False
if a[0] == '-' and b[0] != '-':
negative = True
a, b = b, a
elif a[0] != '-' and b[0] == '-':
negative = False
b = b[1:]
elif a[0] == '-' and b[0] == '-':
negative = False
a, b = a[1:], b[1:]
a, b = b, a
result = ''
carry = 0
i, j = len(a) - 1, len(b) - 1
while i >= 0 or j >= 0:
x = int(a[i]) if i >= 0 else 0
y = int(b[j]) if j >= 0 else 0
num = x - y - carry
if num < 0:
num += 10
carry = 1
else:
carry = 0
result = str(num) + result
i -= 1
j -= 1
while len(result) > 1 and result[0] == '0':
result = result[1:]
for k in range(len(result) - 1, -1, -1):
if (len(result) - k) % 3 == 0 and k > 0:
result = result[:k] + ',' + result[k:]
if negative:
result = '-' + result
return result
print(subtract(a, b))
Python代码通过使用字符串切片、整数运算以及格式化输出等操作,实现了高精度减法并按照要求的格式输出结果。其核心逻辑与Java代码类似,但Python的语法更加简洁灵活。
希望以上解答对您有所帮助。如果您有任何疑问,欢迎在评论区提出。