Reputation: 7396
I'm thinking of a method that calculates the power (base 10 only) of an integer which will be passed as an argument but without using for loops or recursion:
here's the method in it's simplest form using forr loop:
static long power(int val) {
long y = 10l;
if (val == 1) {
return y;
} else {
for (int x = 0; x < val - 1; x++) {
y *= 10;
}
return y;
}
}
Upvotes: 2
Views: 757
Reputation: 838696
The simplest way is to use Math.pow
.
Assuming you don't want to do that, you could use a lookup table. There is only a small finite number of results that fit into a long. Something like this would work:
static final long[] results = { 1L, 10L, 100L, /* etc... */ };
static long power(int val) {
return results[val];
}
Upvotes: 5
Reputation: 158
There might be a way using Strings. Something like...
String zeros = new String(new char[val]).replace('\0', '0');
String init = "1";
String out = init.concat(zeros);
return Long.valueof(out);
But i think replace will also use a loop inside. Maybe Array.fill doesn't (so you can try with char[])
Upvotes: 0
Reputation: 3349
I don't see why you would want to do that, but obviously, this would work:
(warning: as ugly as you want it)
Of course, this only hides loops
Upvotes: 0