return Its corresponding column title as appear in an Excel sheet. For example: 1, A 2, B 3, C ... AA , Z
This problem is my Microsoft onsite encountered a problem, did not encounter this problem is really a bit difficult to understand suddenly (I was the problem should do bad, from most significant digit do, and forget N to-1). This question is actually the decimal conversion 26 binary, and is starting from 1 10 binary conversion
The essence is a binary conversion, converting N to 26, and the conversion process is as follows (26 decimal numbers in parentheses):
1-> (1)->a2-> (2)->b ... 26-> (Ten)->z27-> (one)->aa28-> (a)->ab ..... 52-> (->az53->)->ba
Starting from least significant digit, divide by 26 to take the remainder continuously.
This is my method:
1 Public classSolution {2 PublicString Converttotitle (intN) {3 if(n <= 0)return"";4StringBuffer res =NewStringBuffer ();5 while((n-1)/26 > 0) {6Res.insert (0, (Char) (' A ' + (n-1)%26));7n = (n-1)/26;8 }9Res.insert (0, (Char) (' A ' + (n-1)%26));Ten returnres.tostring (); One } A}
The way people are inspired by others online:
1 Public classSolution {2String Converttotitle (intN) {3StringBuffer str =NewStringBuffer ();4 while(n! = 0){5 intr = N 26;6n= N/26;7 if(r = = 0) {//as an integer multiple of 26, this bit is set to Z,n minus 18Str.insert (0, ' Z ');9n--;Ten } One Else{ AStr.insert (0, (Char) (' A ' +r-1)); - } - } the returnstr.tostring (); - } -}
Leetcode:excel Sheet Column Title