Reputation: 29
for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
Upvotes: 0
Views: 4190
Reputation: 288
You can add n
zeroes to the end of a number, sum
by multiplying sum
by 10 * n
.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
Upvotes: 1
Reputation: 1211
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0
zeros for i = 0, 1, ... n-2, n-1
respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT] The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}
Upvotes: 0
Reputation: 201537
Multiply by 10
instead, and use <
(not >
) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
Upvotes: 0
Reputation: 13
i>array.length
. Since i
starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length
.pow(a,b)
function that computes ab. With that in mind, what you want is something like this:int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Upvotes: 0
Reputation: 13232
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
Upvotes: 0
Reputation: 5647
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum
every iteration. Be careful though, because the max value of an int
is 2^31, so it of surpasses that, it will roll back to 0
Upvotes: 4