171. Excel Sheet Column Number/168. Excel Sheet Column Title(Java/C++)

来源:互联网 发布:人工智能机械假肢感应 编辑:程序博客网 时间:2024/06/06 02:22

171. Excel Sheet Column Number

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

A -> 1B -> 2C -> 3...Z -> 26AA -> 27AB -> 28 

in C++:

class Solution {public:    int titleToNumber(string s) {        int result = 0;        //s.at(i)表示返回下标为i的元素的引用,注意:循环体为空!        for (int i = 0; i < s.size(); result = result * 26 + (s.at(i) - 'A' + 1), i++);         return result;    }};

in Java:

public class Solution {    public int titleToNumber(String s) {        int result = 0;        for (int i = 0; i < s.length(); result = result * 26 + (s.charAt(i) - 'A' + 1), i++);        return result;    }}

168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB 

in C++:

class Solution {public:    string convertToTitle(int n) {        return n == 0 ? "" : convertToTitle((n - 1) / 26) + (char)('A' + (n - 1) % 26);    }};

in Java:

public class Solution {    public String convertToTitle(int n) {        return n == 0 ? "" : convertToTitle((n - 1) / 26) + (char)('A' + (n - 1) % 26);    }}
阅读全文
0 0
原创粉丝点击