Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way to replace digits from Int array?

Tags:

java

If I have two ints Goal - replace last 3 digits of x1 by x2

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));

Question - Is it neccesary to have the three if conditionals, or is there a simpler way to do this?

like image 225
Steveo90 Avatar asked Sep 16 '26 02:09

Steveo90


1 Answers

There is no int array in your code.

Replacing the last three digits of a positive integer by the last three digits of a postitive integer just requires a bit of math :

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

(x1/1000)*1000 zeroes the last 3 digits of x1 because / does integer division when applied to integer types.
x2%1000 results in only the 3 last digits of x2.
And the sum is the result you want.

Things get a bit more complicated if negative numbers are involved.

If we make use of the fact that the question states that x2 can't be greater than 999 we can simplify the code to :

x1 = (x1/1000)*1000 + x2;
like image 178
Anonymous Coward Avatar answered Sep 17 '26 15:09

Anonymous Coward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!