It's a transition from 10 notation to 26 notation. The trick is that counting starts from 1 not 0. So we need to minus 1 to get the right alphabet.
1->A
2->B
26->Z
27->AA
...
52->AZ
In line 6: (n-1)%26 makes result ranges from 0 to 25
e.g. when n=26, (n-1)%26=25;
when n=25, (n-1)%26=24;
when n=1, (n-1)%26=0
In line 7: makes (n-1)/26 =0 when n is from 1 to 26.
e.g. when n=26, (n-1)/26 =0;
when n=1, (n-1)/26 =0;
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public: string convertToTitle(int n) { string result; while(n!=0){ result=(char)('A'+(n-1)%26)+result; n=(n-1)/26; } return result; } }; |
Reference: http://www.cnblogs.com/EdwardLiu/p/4179867.html
没有评论:
发表评论