Reputation: 251
On a project I've been working on, I came across a problem, where I need to append a single digit to an Integer
. The problem is you can't append to an Integer
, with a simple solution like: Integer.append(someArrayOfNumbers)
orsomeDigit.append(aNumber).
And there's not really any good information on it. So I was wanting to know some algorithms and "such".
Upvotes: 1
Views: 13937
Reputation: 48258
if you are appending only one digit to the right side or LSB then you can append by multiplying by ten and adding the new number...
public int append(int originalValue, int numberToAppend ) {
return originalValue*10+ numberToAppend;
}
for more digits you can do using a string concatenation first
public int append(Integer originalValue, Integer numberToAppend ) {
String temp = originalValue.toString()+ numberToAppend.toString();
return Integer.parseInt(temp);
}
Upvotes: 1
Reputation: 271105
One solution is to multiply the int by 10 and add the digit, or if the int is negative, minus the digit:
youtInt * 10 + (yourInt < 0 ? -yourDigit : yourDigit)
If you want to append any number of digits, multiply the int by pow(10, log10(yourDigits) + 1)
.
Another solution is to convert the int to a string and add the digit at the end of the string, and convert it back to an int:
Integer.parseInt(Integer.toString(yourInt) + Integer.toString(yourDigit))
Upvotes: 4
Reputation: 251
Here's my base solution(well part mine, I got some info from this answer but I had to tinker, here), without using a String
. I say base because this algorithm doesn't work properly, if one of the array members, is more than one digit.
public int append(int[] arrayOfIntegers) {
int total;
int length = arrayOfIntegers.length; // for quick reference
total = (int) (arrayOfIntegers[0] * Math.pow(10, length - 1)); // first item times 10 to the power of length minus 1
for (int i = 1; i < length; i++) {
total += arrayOfIntegers[i] * Math.pow(10, length - i - 1);
}
return total;
}
Now to append to an integer:
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
System.out.println("The array appended: " + append(array));
Output:
The array appended: 1234567
Upvotes: 1