7

Write a program to print out all possible values of int data type from the smallest to the largest, using Java.

Some notable solutions as of 8th of May 2009, 10:44 GMT:

1) Daniel Lew was the first to post correctly working code.

2) Kris has provided the simplest solution for the given problem.

3) Tom Hawtin - tackline, came up arguably with the most elegant solution.

4) mmyers pointed out that printing is likely to become a bottleneck and can be improved through buffering.

5) Jay's brute force approach is notable since, besides defying the core point of programming, the resulting source code takes about 128 GB and will blow compiler limits.

As a side note I believe that the answers do demonstrate that it could be a good interview question, as long as the emphasis is not on the ability to remember trivia about the data type overflow and its implications (that can be easily spotted during unit testing), or the way of obtaining MAX and MIN limits (can easily be looked up in the documentation) but rather on the analysis of various ways of dealing with the problem.

7
  • 3
    Was this a real interview question? How awful. I hate useless interview questions. I'd seriously look at them and say "why would anyone ever write that". Commented May 7, 2009 at 16:18
  • There's no way this is a real interview question. Nobody in their right mind would ask this in an interview. Commented May 7, 2009 at 16:23
  • 4
    Some companies use questions like this as a quick weed out question. Usually it's over the phone, but occasionally you'll get one face to face. Don't be so surprised, the questions do get harder. Commented May 7, 2009 at 16:33
  • There is an actual problem here (see answers), but it doesn't seem an efficient way to learn about an interviewee. Commented May 7, 2009 at 16:38
  • 1
    reopen- I guess some people have showed why this is a good interview question Commented May 7, 2009 at 16:40

14 Answers 14

15
class Test { public static void main(String[] args) { for (int a = Integer.MIN_VALUE; a < Integer.MAX_VALUE; a++) { System.out.println(a); } System.out.println(Integer.MAX_VALUE); } } 

Am I hired?

Sign up to request clarification or add additional context in comments.

10 Comments

I wouldn't, ;) just because you have an extra line for no reason whatsoever. Why not just: for (int a = Integer.MIN_VALUE; a <= Integer.MAX_VALUE; a++) { System.out.println(a); }
If you don't add that last line, your loop will never terminate. Using your method, when a == Integer.MAX_VALUE, you'll print it, increment a, and suddenly a will be Integer.MIN_VALUE.
Matthew Flaschen, you have fallen victim to one of the classic blunders
So you'd add an extra conditional check to every single iteration, instead of just printing the max value at the end? And you think that's an improvement?
@Dave: Why would I change my answer when Kris has already used that exact method? It's helpful to no one if everyone edits their answers to be the same thing, especially when both of our answers are valid. Besides, my solution is easily translatable into "print all values of long", whereas a version that uses long would have to move to BigInt to use the same solution (and would consequently be a lot slower).
|
14

Simplest form (minimum code):

 for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) { System.out.println(i); } 

No integer overflow, no extra checks (just a little more memory usage, but who doesn't have 32 spare bits lying around).

While I suppose

 for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) System.out.println(i); 

has fewer characters, I can't really say that it is simpler. Shorter isn't necessarily simpler, it does have less code though.

7 Comments

Will never terminate (see previous answers).
Nicely done. 32 bits is nothing, especially on a 64bit architecture where, depending on the VM, you would just waste more memory.
/me needs to learn to read. Sorry, my internet connection is crazy slow today and it's driving me to distraction. Please ignore me while I spout nonsense. :)
You totally dont need those carriage returns or curly braces!
Another curveball - With "server" VM, it will actually terminate in the middle. There is a HotSpot bug that will convert 'i <= Integer.MAX_INT' ( which may require two comparison '<' and '=' ) into 'i < Integer.MAX_INT + 1'. Because it will overflow and turn into negative number, the loop will just terminate. However, this is not the case -client mode.
|
8

I just have to add an answer...

public class PrintInts { public static void main(String[] args) { int i = Integer.MIN_VALUE; do { System.out.println(i); ++i; } while (i != Integer.MIN_VALUE); } } 
  • We don't want the body repeated (think of the maintenance!)
  • It doesn't loop forever.
  • It uses an appropriate type for the counter.
  • It doesn't require some wild third-party weirdo library.

Comments

4

Ah, and here I had just started writing

System.out.println(-2147483648); System.out.println(-2147483647); System.out.println(-2147483646); 

Okay, just give me a few weeks to finish typing this up ...

The instructions didn't say I have to use a loop, and at least this method doesn't have any overflow problems.

2 Comments

Write a program to write that program for you!
@Totophil: But my company measure productivity by lines of code. By the time I get this program done, I'll be #1 in the department.
4

Is there something tricky that I'm not catching? There probably is... (edit: yes, there is!)

class AllInts { public static void main(String[] args) { // wrong -- i <= Integer.MAX_VALUE will never be false, since // incrementing Integer.MAX_VALUE overflows to Integer.MIN_VALUE. for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) { System.out.println(i); } } } 

Since the printing is the bottleneck, a buffer would improve the speed quite a lot (I know because I just tried it):

class AllInts { public static void main(String[] args) { // a rather large cache; I did no calculations to optimize the cache // size, but adding the first group of numbers will make the buffer // as large as it will ever need to be. StringBuilder buffer = new StringBuilder(10000000); int counter = 0; // note that termination check is now < // this means Integer.MAX_VALUE won't be printed in the loop for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { buffer.append(i).append('\n'); if (++counter > 5000000) { System.out.print(buffer); buffer.delete(0, buffer.length()-1); counter = 0; } } // take care of the last value (also means we don't have to check // if the buffer is empty before printing it) buffer.append(Integer.MAX_VALUE); System.out.println(buffer); } } 

Also, this version will actually terminate (thanks to Daniel Lew for pointing out that there was, in fact, something tricky that I wasn't catching).

The total run time for this version (run with -Xmx512m) was 1:53. That's over 600000 numbers/second; not bad at all! But I suspect that it would have been slower if I hadn't run it minimized.

5 Comments

Your loop will never terminate.
Java is subject to integer overflow, and so when i == Integer.MAX_VALUE, it will be incremented by one and overflow into Integer.MIN_VALUE
Ah, there was something tricky. I thought it was merely for performance that you use a < instead of a <=. (And my second version is a lot faster than yours, if it matters. ;)
Well, it prints faster, but it sure doesn't finish earlier. ;)
The second version (with a bigger buffer, actually) took about two and a half hours to complete. And it does stop at 2147483647 like it should.
3

When I first looked at this, my first question was 'how do you define smallest and largest'. For what I thought was the most obvious definition ('smallest' == 'closest to 0') the answer would be

for (int i = 0; i >= 0; i++) { System.out.println(i); System.out.println(-i-1); } 

But everyone else seems to read 'smallest' as 'minimum' and 'largest' as 'maximum'

1 Comment

I read the question the same way. Integer.MIN_VALUE is not a small number, it is a very large negative number.
3

Come on folks, it said using java. It didn't say use an int in the for loop. :-)

public class Silly { public static void main(String[] args) { for (long x = Integer.MIN_VALUE; x <= Integer.MAX_VALUE; x++) { System.out.println(x); } } } 

Comments

3

Another way to loop through every value using an int type.

public static void main(String[] args) { int i = Integer.MIN_VALUE; do { System.out.println(i); } while (i++ < Integer.MAX_VALUE); } 

Comments

2

Given the overview of the best answers, I realized that we're seriously lacking in the brute-force department. Jay's answer is nice, but it won't actually work. In the name of Science, I present - Bozo Range:

import java.util.Random; import java.util.HashSet; class Test { public static void main(String[] args) { Random rand = new Random(); HashSet<Integer> found = new HashSet<Integer>(); long range = Math.abs(Integer.MAX_VALUE - (long) Integer.MIN_VALUE); while (found.size() < range) { int n = rand.nextInt(); if (!found.contains(n)) { found.add(n); System.out.println(n); } } } } 

Note that you'll need to set aside at least 4 GB of RAM in order to run this program. (Possibly 8 GB, if you're on a 64-bit machine, which you'll probably require to actually run this program...). This analysis doesn't count the bloat that the Integer class adds to any given int, either, nor the size of the HashSet itself.

2 Comments

Upvoted for the sheer fun on it. One of the key benefits I see behind this approach is the usage of standard collections library, meaning, for example, that you could easilly sort the numbers if you had to before outputting them...
Am I missing something, or can't pagefiles be used to allow it to have less than 4GB of RAM?
2

The maximum value for int is Integer.MAX_VALUE and the minimum is Integer.MIN_VALUE. Use a loop to print all of them.

1 Comment

That's 2 English sentences, not a Java program. :-)
1

Package fj is from here.

import static fj.pre.Show.intShow; import static fj.pre.Show.unlineShow; import static fj.data.Stream.range; import static java.lang.Integer.MIN_VALUE; import static java.lang.Integer.MAX_VALUE; public class ShowInts {public static void main(final String[] args) {unlineShow(intShow).println(range(MIN_VALUE, MAX_VALUE + 1L));}} 

1 Comment

Sure, but why would you add an additional dependency for something as trivial as this?
0

At 1000 lines/sec you'll be done in about 7 weeks. Should we get coffee now?

3 Comments

That's not a problem. it should produce output faster than you can read it. Have fun.
Actually, it's closer to 10000 lines/sec (at least with buffering). That's about 5 days. :D
Actual time was about 2 1/2 hours with buffered output. That's more like 4 or 500000 lines/sec. Maybe it was faster because it was minimized.
0

Just improving the StringBuilder's approach a little:

2 threads + 2 buffers (i.e. StringBuilder): The main idea is that one thread fills one buffer while the other thread dumps the content of the other buffer.

Obviously, the "dumper" thread will always run slower than the "filler" thread.

2 Comments

What happens when you run out of memory? Pause the "filler" thread?
Out Of Memory? I have not specified the size of the buffers, the -Xms parameters... I think that 2 buffers with chars 16bit wide, some internal gaps and buffers... I hope that new StringBuilder(15*1024*1024) is a safe choice for a 64MB (default?) VM without having OOMs.
0

If the interviewer was looking for all the Integer values possible in Java, You might try giving him a solution using Long:

class AllIntegers{ public static void main(String[] args) { for (int i = Integer.MIN_VALUE; i < Long.MAX_VALUE; i++) { System.out.println(i); } System.out.println(Long.MAX_VALUE); } } 

This should print a range from -9223372036854775808 to 9223372036854775807 which is way more than you would achieve using Integer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.