Display numbers from 1 to 100 without loops or conditions [closed]
Solution 1:
Know your libraries.
public class To100 {
public static void main(String[] args) {
String set = new java.util.BitSet() {{ set(1, 100+1); }}.toString();
System.out.append(set, 1, set.length()-1);
}
}
(You can use String.replaceAll
to change the separator. For instance, .replaceAll(", ", " ")
for space separation.)
Explanation:
-
java.util.BitSet
is a handy little class that represents an arbitrarily large (non-sparse) set of positive integers. (It does have so bad bits: not final, unnecessarily thread-safe, doesn't support building well, etc.)ta. - Extends
BitSet
allows me to writejava.util
only once. The JDK7 "diamond operator" should help reduce duplication with generic types, but no help for the more common situation. :( - The double braces are the Double Brace idiom - an anonymous inner class containing only an instance initialiser. It is a hack. It increase runtime size, and hence start-up time. Distribution size is negligible if you use pack200.gz. I think the modern world is ready for it. Your colleagues may not be. Perhaps start by using it for test da
-
BitSet.set
sets a bit in the set (two completely different meanings of the word "set" there - I like it). It's a half-open range - the top value exclusive; the bottom inclusive. Add 1 to the top to include 100. -
BitSet.toString
is actually precisely defined by the API docs. -
append
was added toPrintStream
with the introduction of theAppendable
interface in J2SE 5.0. It essentially does a substring and prints the result. (A little secret: this isn't actually guaranteed by the spec to flush the output, but implementations always will.) - Starting the append at 1, and taking one off the length strips the braces from the string representation of
BitSet
. - "Know your libraries." Taken from Josh Bloch. See Java Puzzlers, puzzle 94. It really is good to know what is in the libraries. At least know where to look. Save your time, save maintenance time and get it right first time.
Solution 2:
DO NOT DO THIS UNDER ANY SANE CIRCUMSTANCES!
public class Fail {
public void thisFails(int x){
System.out.println(x);
Integer[] bigArray = new Integer[9450];
thisFails(x+1);
}
public static void main(String[] args) {
Fail failure = new Fail();
failure.thisFails(1);
}
}
When this is ran using 1m of heap space (java -Xmx1m Fail) it will run out of heap at the 100th recursion.
...
I will now go wash my hands.
Solution 3:
Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"?
I can't believe noone suggested this yet:
System.out.println("numbers from 1 to 100 without using any loops or conditions like \"if\"?");