Post date: Oct 19, 2013 9:31:47 AM
Problem
/*
Given an integer N, print numbers from 1 to N in lexicographic order.
Details: To be implemented without using character conversion (or Strings).
Example:
N = 25
Print:
1
10
11
..
19
2
20
21
..
25
3
4
5
6
7
8
9
A simple solution using Strings (may not be acceptable):
System.out.print("\n\tLexicographic Order\n\nEnter an integer: ");
Scanner input = new Scanner(System.in);
Integer n = input.nextInt();
List<String> list = new ArrayList<String>();
for (int i = 1;i<n;i++){
list.add(""+i);
}
Collections.sort(list);
for (String j: list){
System.out.println(j);
}
- Abhi on October 04, 2013 in United States Report Duplicate | Flag
*/
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Given an integer N, print numbers from 1 to N in lexicographic order.
Created Date : 19-10-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <cassert>
using namespace std;
void Print(int n)
{
for(int i = 1; i <= 9; i ++){
int j = 1;
while( j <= n){
for(int m = 0; m < j ; ++ m){
if(m + j * i <= n){
cout << m + j * i << endl;
}
}
j *= 10;
}
}
}
int main()
{
Print(10);
cout << "------------" << endl;
Print(25);
cout << "------------" << endl;
Print(30);
cout << "------------" << endl;
Print(100);
cout << "------------" << endl;
}
Output
1
10
2
3
4
5
6
7
8
9
------------
1
10
11
12
13
14
15
16
17
18
19
2
20
21
22
23
24
25
3
4
5
6
7
8
9
------------
1
10
11
12
13
14
15
16
17
18
19
2
20
21
22
23
24
25
26
27
28
29
3
30
4
5
6
7
8
9
------------
1
10
11
12
13
14
15
16
17
18
19
100
2
20
21
22
23
24
25
26
27
28
29
3
30
31
32
33
34
35
36
37
38
39
4
40
41
42
43
44
45
46
47
48
49
5
50
51
52
53
54
55
56
57
58
59
6
60
61
62
63
64
65
66
67
68
69
7
70
71
72
73
74
75
76
77
78
79
8
80
81
82
83
84
85
86
87
88
89
9
90
91
92
93
94
95
96
97
98
99
------------
Press any key to continue . . .
Simple solution