gpt4 book ai didi

java - 从 Int 数组中替换数字的更简单方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:40 24 4
gpt4 key购买 nike

如果我有两个整数目标 - 用 x2 替换 x1 的最后 3 位

int x1 = 1000;
int x2 = 3; //x2 can't be larger than 999

char[] digits = String.valueOf(x1).toCharArray();
char[] digits2 = String.valueOf(x2).toCharArray();

if(digits2.length == 3) {
replace digits[1],[2],[3] by digits[0,1,2]
}
if(digits2.length == 2) {
replace digits[2,3] by digits[0,1] and replace digits[1] by 0
}
if(digits.length == 1) {
replace digits[3] by digits[0] and digits[1,2,] by 0
}

x1 = Integer.parseInt(new String(digits));

问题 - 是否需要三个 if 条件,或者是否有更简单的方法来做到这一点?

最佳答案

您的代码中没有 int 数组。

用正整数的最后三位替换正整数的最后三位只需要一点数学知识:

x1 = (x1/1000)*1000 + x2%1000;

(x1/1000)*1000x1 的最后 3 位归零,因为/在应用于整数类型时进行整数除法。
x2%1000 仅产生 x2 的最后 3 位数字。
求和就是你想要的结果。

如果涉及负数,事情会变得有点复杂。

如果我们利用问题指出 x2 不能大于 999 这一事实,我们可以将代码简化为:

x1 = (x1/1000)*1000 + x2;

关于java - 从 Int 数组中替换数字的更简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com