本文主要是介绍LeetCode171 Excel Sheet Column Number,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目要求:
Excel Sheet Column Number
Related to question Excel Sheet Column TitleGiven a column title as appear in an Excel sheet, return its corresponding column number.For example:A -> 1B -> 2C -> 3...Z -> 26AA -> 27AB -> 28
简介算法
public class solution_new {public int titleToNumber(String s) {int sum = 0;int N = s.length() - 1;for(char c : s.toCharArray()) {System.out.println(c);sum += (c - 'A' + 1) * Math.pow(26, N--);}return sum;}
}
比较麻烦的一种解法(效率较好)
import java.util.ArrayList;
import java.util.List;public class solution {public int titleToNumber(String s) {ArrayList<Integer> list = new ArrayList<Integer>();int sum = 0;for(int i = 0; i < s.length(); i++) {list.add(s.charAt(i) - 'A' + 1);}int tol = list.size();if(tol > 1) {sum = summer(list);}else {sum = list.get(tol - 1);}return sum;}/*** 这个方法用于处理26进制的加法运算,使用了递归处理* @param arr* @return int sum*/public int summer(ArrayList<Integer> arr) {int sum = 0;for(int i = 0; i < arr.size(); i++) {sum = sum * 26 + arr.get(i);}return sum;}
}
这篇关于LeetCode171 Excel Sheet Column Number的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!