1
1
package com .fishercoder .solutions ;
2
- /**168. Excel Sheet Column Title
2
+ /**
3
3
*
4
- Given a positive integer, return its corresponding column title as appear in an Excel sheet.
4
+ * 168. Excel Sheet Column Title
5
5
6
- For example:
6
+ Given a positive integer, return its corresponding column title as appear in an Excel sheet.
7
7
8
- 1 -> A
9
- 2 -> B
10
- 3 -> C
11
- ...
12
- 26 -> Z
13
- 27 -> AA
14
- 28 -> AB */
15
- public class _168 {
8
+ For example:
16
9
17
- public String convertToTitle_accepted_more_beautiful (int n ) {
18
- /**Get the right most digit first, move to the left, e.g. when n = 28, we get 'B' first, then we get 'A'.*/
19
- StringBuilder sb =new StringBuilder ();
20
- while (n !=0 ) {
21
- int temp = (n -1 ) %26 ;
22
- sb .append ((char ) (temp +65 ));
23
- n = (n -1 ) /26 ;
24
- }
25
- return sb .reverse ().toString ();
10
+ 1 -> A
11
+ 2 -> B
12
+ 3 -> C
13
+ ...
14
+ 26 -> Z
15
+ 27 -> AA
16
+ 28 -> AB
17
+ ...
26
18
27
- }
19
+ Example 1:
28
20
29
- public static void main (String ...strings ) {
30
- _168 test =new _168 ();
31
- // int n = 28899;
32
- // int n = 1;
33
- // int n = 1000000001;
34
- // int n = 26;
35
- // int n = 27;
36
- int n =28 ;
37
- // int n = 52;
38
- // int n = 53;
39
- // System.out.println((int) 'A');
40
- // System.out.println(1000000001/26);
41
- // System.out.println(25*26);
42
- // System.out.println(26*26);
43
- // System.out.println(27*26);
44
- // System.out.println(702%26);
45
- // System.out.println(702/26);
46
- System .out .println (Integer .parseInt (String .valueOf (26 ),10 ));
47
- System .out .println (test .convertToTitle_accepted_more_beautiful (n ));
48
- }
21
+ Input: 1
22
+ Output: "A"
49
23
50
- public String convertToTitle_accepted (int n ) {
51
- /**'Z' is the corner case, so we'll have to special case handling specially, also, we'll have to do (n-1)/26,
52
- * only when this is not equal to 1, we'll continue.*/
53
- StringBuilder sb =new StringBuilder ();
54
- while (n !=0 ) {
55
- int temp =n %26 ;
56
- if (temp ==0 ) {
57
- sb .append ("Z" );
58
- }else {
59
- sb .append ((char ) (temp +64 ));
60
- }
61
- n = (n -1 ) /26 ;
62
- }
63
- return sb .reverse ().toString ();
64
- }
24
+ Example 2:
25
+
26
+ Input: 28
27
+ Output: "AB"
65
28
66
- }
29
+ Example 3:
30
+
31
+ Input: 701
32
+ Output: "ZY"
33
+
34
+ */
35
+ public class _168 {
36
+ public static class Solution1 {
37
+ public String convertToTitle (int n ) {
38
+ /**Get the right most digit first, move to the left, e.g. when n = 28, we get 'B' first, then we get 'A'.*/
39
+ StringBuilder sb =new StringBuilder ();
40
+ while (n !=0 ) {
41
+ int temp = (n -1 ) %26 ;
42
+ sb .append ((char ) (temp +65 ));
43
+ n = (n -1 ) /26 ;
44
+ }
45
+ return sb .reverse ().toString ();
46
+ }
47
+ }
48
+ }