Doing something you intrinsically are enthusiastic with.

2016年8月25日 星期四

Leetcode--Excel Sheet Column Title

中午12:39 Posted by Unknown No comments
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

Solution:

This is a 26-ary system. However if we use 1-26. 26 can not be consistent with other numbers ahead.

For example: 25/26=0, but 26/26=1. So we need to apply 0-based policy in this problem.

Each number from 1-26 minuses 1 to conform A-Z. But new problems occur, AA should be 27

orginally, 27-1=26, 26%26=0. This is incorrect. So every number should minus 1 in each loop to

make sure it's 0-based.

  1. class Solution {
  2. public:
  3.     string convertToTitle(int n) {
  4.        
  5.         string ans;
  6.         while (n--!= 0) {
  7.             ans = char(int('A') + n % 26) + ans;
  8.             n /= 26;
  9.         }
  10.         return ans;
  11.  
  12.     }
  13. };

0 意見:

張貼留言