So the purpose of this question is to print out N integers in String Order. For example, if N is 1000, then we will output: 1, 10, 100, 1000, 101, 102, … 109, 11, 110, …
First off we are going to run off an assumption given in the example. We are printing only positive integers!.
Secondly, let’s try to examine what is happening here. We need to print lower digit numbers first and then all numbers formed of this number + attached 1-10. Seeing as this is a recurring action that we do, a recursive algorithm would fit perfectly!
From this we can have the following recursive algorithm:
- Main method – loop through 1 to 9
- Recursive method – print current number, + current number + an in order number from 1-10
Printing N Integers in String Order รขโฌโ first and final try
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* * @Author: Ajk Palikuqi * * @Question: How to Print N Integers in String Order * */ package iqLib.stringLib; public class IntegersInStringOrder { public static void PrintIntegersInStringOrder(int N) { if (N < 1) { return; } for (int i = 1; i < 10; ++i) { PrintIntegersInStringOrderInRecursion("" + i, N); } } public static void PrintIntegersInStringOrderInRecursion(String currNum, int N) { if (Integer.parseInt(currNum) > N) { return; } System.out.println(currNum); for (int i = 0; i < 10; ++i) { PrintIntegersInStringOrderInRecursion(currNum + i, N); } } } |
Great! Now we all know how to print N Integers in String Order! A quick editing of the algorithm, makes sure that we do not go over our N numners.
Hope you guys enjoyed it… and I’ll see you guys next time ;D
Latest posts by Ajk (see all)
- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017