1. 根據輸入的字符串序列,返回對應的值,形式如下:
來源:力扣(LeetCode)
給定一個Excel表格中的列名稱,返回其相應的列序號。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
package com.example.study;
import java.util.Scanner;
/**
*author:bingbing
*日期:2020年7月3日
*時間:下午9:44:37
*給定一個Excel表格中的列名稱,返回其相應的列序號。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
*
*/
public class Demo02 {
public static void main(String[] args) {
System.out.println("請輸入excel裏面的列名稱: 字符串形式");
String str="";
Scanner scanner=new Scanner(System.in);
str=scanner.nextLine();
int result=getResultByStr(str);
System.out.println("結果爲:"+result);
scanner.close();
}
//輸入字符串得到數字,如輸入AA,表示27,A爲65
private static int getResultByStr(String str) {
int sum=0;
for(int i=0;i<str.length();i++) {
int num=str.charAt(i)-'A'+1;
System.out.println(num);
sum=26*sum+num;
}
return sum;
}
}