Write a function that takes an integer as input and produces an output string.
Some sample Input/outputs are as follows
i/p o/p
1 - A
2 - B
3 - AA
4 - AB
5 - BA
6 - BB
7 - AAA
8 - AAB
9 - ABA
10 - ABB
11 - BAA
12 - BAB
13 - BBA
14 - BBB
15 - AAAA
This looks like an integer to binary conversion, however, instead of using 0, 1 representation, it would be easier to understand if we convert in this way:
A 1
B 2
AA 11
AB 12
BA 21
If we use binary representations, we will have:
A 1
B 10
AA 11
AB 110
BA 101
It is reasonable that when n % 2 = 1, we append "A". However, if n % 2 = 0, we will have one extra digit, so we need to subtract 1 before we divide by 2.
public class IntegerToString { public static String convert(int n){ if(n <= 0) return null; String rst = ""; while(n > 0){ if((n & 1) != 0) rst = "A" + rst; else { rst = "B" + rst; n -= 1; } n = (n >> 1); } return rst; } public static void main(String[] args) { for(int i = 1; i <= 15; i++) System.out.println(convert(i)); } }
No comments:
Post a Comment