【LeetCode】171. Excel Sheet Column Number && 168. Excel Sheet Column Title
2016-03-08 19:38
405 查看
171.Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
168.Given a positive integer, return its corresponding column title as appear in an Excel sheet.For example:
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
class Solution { public: int titleToNumber(string s) { if(s.size()==0) return 0; int result = 0; for(int i =0; i < s.length(); i++) { int tmp = s[i] - 64; result += pow(26,s.length()-i-1)*tmp; } return result; } };
168.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
class Solution { public: //本质是从一个10进制数转换成26进制,由于下标从1开始而不是从0开始,因此要减一操作 string convertToTitle(int n) { string s=""; if(n <=0) return 0; while(n>0) { int tmp = (n-1)%26; s += tmp + 65; n = (n-1) / 26; } reverse(s.begin(),s.end()); return s; } };
相关文章推荐