本文概述
- C ++
- Java
- Python3
- C#
给定列标题(如Excel工作表中所示), 返回其对应的列号。
columncolumn number
A->
1
B->
2
C->
3
...
Z->
26
AA ->
27
AB ->
28
例子:
Input: A
Output: 1
A is the first column so the output is 1.Input: AA
Output: 27
The columns are in order A, B, ..., Y, Z, AA ..
So, there are 26 columns after which AA comes.
方法:
该过程类似于二进制到十进制的转换。
例如, 要转换AB, 公式为26 * 1 + 2。
再举一个例子
To convert CDA, 3*26*26 + 4*26 + 1
= 26(3*26 + 4) + 1
= 26(0*26 + 3*26 + 4) + 1
因此, 这非常类似于将二进制数转换为十进制(将基数保持为26)。
将输入作为字符串, 然后从左到右遍历输入字符串, 并计算结果, 如下所示:
result = 26*result + s[i] - 'A' + 1
.
结果将是
文章图片
.
C ++
// C++ program to return title to result
// of excel sheet.
#include <
bits/stdc++.h>
using namespace std;
// Returns resul when we pass title.
int titleToNumber(string s)
{
// This process is similar to
// binary-to-decimal conversion
int result = 0;
for ( const auto &
c : s)
{
result *= 26;
result += c- 'A' + 1;
}return result;
}// Driver function
int main()
{
cout <
<
titleToNumber( "CDA" ) <
<
endl;
return 0;
}
Java
// Java program to return title
// to result of excel sheet.
import java.util.*;
import java.lang.*;
class GFG
{// Returns resul when we pass title.
static int titleToNumber(String s)
{
// This process is similar to
// binary-to-decimal conversion
int result = 0 ;
for ( int i = 0 ;
i <
s.length();
i++)
{
result *= 26 ;
result += s.charAt(i) - 'A' + 1 ;
}
return result;
}// Driver Code
public static void main (String[] args)
{
System.out.print(titleToNumber( "CDA" ));
}
}// This code is contributed
// by Akanksha Rai(Abby_akku)
Python3
# Python program to return title to result
# of excel sheet. # Returns resul when we pass title.
def titleToNumber(s):
# This process is similar to binary-to-
# decimal conversion
result = 0 ;
for B in range ( len (s)):
result * = 26 ;
result + = ord (s[B]) - ord ( 'A' ) + 1 ;
return result;
# Driver function
print (titleToNumber( "CDA" ));
# This code contributed by Rajput-Ji
C#
// C# program to return title
// to result of excel sheet.
using System;
class GFG
{// Returns resul when we pass title.
public static int titleToNumber( string s)
{
// This process is similar to
// binary-to-decimal conversion
int result = 0;
for ( int i = 0;
i <
s.Length;
i++)
{
result *= 26;
result += s[i] - 'A' + 1;
}
return result;
}// Driver Code
public static void Main( string [] args)
{
Console.Write(titleToNumber( "CDA" ));
}
}// This code is contributed by Shrikant13
输出如下:
2133
复杂度分析:
- 时间复杂度:O(n), 其中n是输入字符串的长度。
- 空间复杂度:O(1)。
由于不需要额外的空间。
推荐阅读
- OOP(Java如何使用封装(用法解析和示例))
- JavaScript如何从数组中删除最后一项()
- Python MySQL如何使用select查询(代码示例)
- 如何从Python中的列表中删除多个元素(完整实现)
- Golang如何使用结构体指针(代码示例)
- JavaScript如何使用导入和导出模块(代码示例)
- 代码转换器– BCD(8421)到/从Excess-3
- Win8.1系统还原后提示Windows无法激活的处理方案
- Win8.1下载软件一直提示缺少“ATL100.DLL”文件如何处理?