📜  从给定的列号中查找 Excel 列名

📅  最后修改于: 2022-05-13 01:57:07.817000             🧑  作者: Mango

从给定的列号中查找 Excel 列名

MS Excel 列具有 A、B、C、...、Z、AA、AB、AC、...、AZ、BA、BB、... ZZ、AAA、AAB ..... 等模式。换句话说,第 1 列是命名为“A”,第 2 栏为“B”,第 27 栏为“AA”。
给定一个列号,找到其对应的 Excel 列名。以下是更多示例。

Input          Output
 26             Z
 51             AY
 52             AZ
 80             CB
 676            YZ
 702            ZZ
 705            AAC

感谢 Mrigank Dembla 在评论中提出以下解决方案。
假设我们有一个数字 n,比如说 28。所以对应它我们需要打印列名。我们需要用 26 取余数。

如果 26 的余数为 0(表示 26、52 等),那么我们将“Z”放入输出字符串中,新的 n 变为 n/26 -1,因为这里我们将 26 视为“Z”,而实际上,它是“A”的第 25 位。

同样,如果余数不为零。 (如 1、2、3 等)然后我们只需在字符串中相应地插入字符并执行 n = n/26。

最后,我们反转字符串并打印。

例子:
n = 700
余数 (n%26) 是 24。所以我们将“X”放入输出字符串中,n 变为 n/26,即 26。
余数 (26%26) 为 0。因此我们将“Z”放入输出字符串中,n 变为 n/26 -1,即 0。

以下是上述方法的实现。

C++
// C++ program to find Excel
// column name from a given
// column number
#include 
#define MAX 50
using namespace std;
 
// Function to print Excel column name for a given column number
void printString(int n)
{
    char str[MAX]; // To store result (Excel column name)
    int i = 0; // To store current index in str which is result
 
    while (n > 0) {
        // Find remainder
        int rem = n % 26;
 
        // If remainder is 0, then a 'Z' must be there in output
        if (rem == 0) {
            str[i++] = 'Z';
            n = (n / 26) - 1;
        }
        else // If remainder is non-zero
        {
            str[i++] = (rem - 1) + 'A';
            n = n / 26;
        }
    }
    str[i] = '\0';
 
    // Reverse the string and print result
    reverse(str, str + strlen(str));
    cout << str << endl;
 
    return;
}
 
// Driver program to test above function
int main()
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
    return 0;
}


Java
// Java program to find Excel
// column name from a given
// column number
 
public class ExcelColumnTitle {
    // Function to print Excel column
    // name for a given column number
    private static void printString(int columnNumber)
    {
        // To store result (Excel column name)
        StringBuilder columnName = new StringBuilder();
 
        while (columnNumber > 0) {
            // Find remainder
            int rem = columnNumber % 26;
 
            // If remainder is 0, then a
            // 'Z' must be there in output
            if (rem == 0) {
                columnName.append("Z");
                columnNumber = (columnNumber / 26) - 1;
            }
            else // If remainder is non-zero
            {
                columnName.append((char)((rem - 1) + 'A'));
                columnNumber = columnNumber / 26;
            }
        }
 
        // Reverse the string and print result
        System.out.println(columnName.reverse());
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        printString(26);
        printString(51);
        printString(52);
        printString(80);
        printString(676);
        printString(702);
        printString(705);
    }
}
 
// This code is contributed by Harikrishnan Rajan


Python
# Python program to find Excel column name from a
# given column number
 
MAX = 50
 
# Function to print Excel column name
# for a given column number
def printString(n):
 
    # To store result (Excel column name)
    string = ["\0"] * MAX
 
    # To store current index in str which is result
    i = 0
 
    while n > 0:
        # Find remainder
        rem = n % 26
 
        # if remainder is 0, then a
        # 'Z' must be there in output
        if rem == 0:
            string[i] = 'Z'
            i += 1
            n = (n / 26) - 1
        else:
            string[i] = chr((rem - 1) + ord('A'))
            i += 1
            n = n / 26
    string[i] = '\0'
 
    # Reverse the string and print result
    string = string[::-1]
    print "".join(string)
 
# Driver program to test the above Function
printString(26)
printString(51)
printString(52)
printString(80)
printString(676)
printString(702)
printString(705)
 
# This code is contributed by BHAVYA JAIN


C#
// C# program to find Excel
// column name from a given
// column number
using System;
 
class GFG{
     
static String reverse(String input)
{
    char[] reversedString = input.ToCharArray();
    Array.Reverse(reversedString);
    return new String(reversedString);
}
 
// Function to print Excel column
// name for a given column number
private static void printString(int columnNumber)
{
     
    // To store result (Excel column name)
    String columnName = "";
 
    while (columnNumber > 0)
    {
         
        // Find remainder
        int rem = columnNumber % 26;
 
        // If remainder is 0, then a
        // 'Z' must be there in output
        if (rem == 0)
        {
            columnName += "Z";
            columnNumber = (columnNumber / 26) - 1;
        }
         
        // If remainder is non-zero
        else
        {
            columnName += (char)((rem - 1) + 'A');
            columnNumber = columnNumber / 26;
        }
    }
 
    // Reverse the string
    columnName = reverse(columnName);
     
    // Print result
    Console.WriteLine(columnName.ToString());
}
 
// Driver code
public static void Main(String[] args)
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
}
}
 
// This code is contributed by amal kumar choubey


Javascript


C++
#include 
using namespace std;
 
void printString(int n)
{
    int arr[10000];
    int i = 0;
 
    // Step 1: Converting to number assuming
    // 0 in number system
    while (n) {
        arr[i] = n % 26;
        n = n / 26;
        i++;
    }
 
    // Step 2: Getting rid of 0, as 0 is
    // not part of number system
    for (int j = 0; j < i - 1; j++) {
        if (arr[j] <= 0) {
            arr[j] += 26;
            arr[j + 1] = arr[j + 1] - 1;
        }
    }
 
    for (int j = i; j >= 0; j--) {
        if (arr[j] > 0)
            cout << char('A' + arr[j] - 1);
    }
 
    cout << endl;
}
 
// Driver program to test above function
int main()
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
    return 0;
}
 
// This code is contributed by Ankur Goel


Java
import java.util.*;
 
class GFG{
 
static void printString(int n)
{
    int []arr = new int[10000];
    int i = 0;
 
    // Step 1: Converting to number
    // assuming 0 in number system
    while (n > 0)
    {
        arr[i] = n % 26;
        n = n / 26;
        i++;
    }
 
    // Step 2: Getting rid of 0, as 0 is
    // not part of number system
    for(int j = 0; j < i - 1; j++)
    {
        if (arr[j] <= 0)
        {
            arr[j] += 26;
            arr[j + 1] = arr[j + 1] - 1;
        }
    }
 
    for(int j = i; j >= 0; j--)
    {
        if (arr[j] > 0)
            System.out.print(
                (char)('A' + arr[j] - 1));
    }
    System.out.println();
}
 
// Driver code
public static void main(String[] args)
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
}
}
 
// This code is contributed by amal kumar choubey


Python3
def printString(n):
     
    arr = [0] * 10000
    i = 0
 
    # Step 1: Converting to number
    # assuming 0 in number system
    while (n > 0):
        arr[i] = n % 26
        n = int(n // 26)
        i += 1
         
    #Step 2: Getting rid of 0, as 0 is
    # not part of number system
    for j in range(0, i - 1):
        if (arr[j] <= 0):
            arr[j] += 26
            arr[j + 1] = arr[j + 1] - 1
 
    for j in range(i, -1, -1):
        if (arr[j] > 0):
            print(chr(ord('A') +
                  (arr[j] - 1)), end = "");
 
    print();
 
# Driver code
if __name__ == '__main__':
     
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
 
# This code is contributed by Princi Singh


C#
using System;
class GFG{
 
static void printString(int n)
{
  int []arr = new int[10000];
  int i = 0;
 
  // Step 1: Converting to
  // number assuming 0 in
  // number system
  while (n > 0)
  {
    arr[i] = n % 26;
    n = n / 26;
    i++;
  }
 
  // Step 2: Getting rid of 0,
  // as 0 is not part of number
  // system
  for(int j = 0; j < i - 1; j++)
  {
    if (arr[j] <= 0)
    {
      arr[j] += 26;
      arr[j + 1] = arr[j + 1] - 1;
    }
  }
 
  for(int j = i; j >= 0; j--)
  {
    if (arr[j] > 0)
      Console.Write((char)('A' +
                     arr[j] - 1));
  }
  Console.WriteLine();
}
 
// Driver code
public static void Main(String[] args)
{
  printString(26);
  printString(51);
  printString(52);
  printString(80);
  printString(676);
  printString(702);
  printString(705);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


Python3
# Or you can simply take a string and perform this logic ,no issue i found in here.
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# defined a recursive function here.
# if number is less than "26", simply hash out (index-1)
# There are sub possibilities in possibilities,
# 1.if remainder is zero(if quotient is 1 or not 1) and
# 2. if remainder is not zero
 
def num_hash(num):
    if num < 26:
        return alpha[num-1]
    else:
        q, r = num//26, num % 26
        if r == 0:
            if q == 1:
                return alpha[r-1]
            else:
                return num_hash(q-1) + alpha[r-1]
        else:
            return num_hash(q) + alpha[r-1]
 
 
# Calling the function out here and printing the ALphabets
# This code is robust ,work for any positive integer only.
# You can try as much as you want
print(num_hash(26))
print(num_hash(51))
print(num_hash(52))
print(num_hash(80))
print(num_hash(676))
print(num_hash(702))
print(num_hash(705))


输出
Z
AY
AZ
CB
YZ
ZZ
AAC

方法二
这个问题类似于将十进制数转换为其二进制表示,但不是二进制基本系统,其中我们只有 0 和 1 两个数字,这里我们有来自 AZ 的 26 个字符。
所以,我们处理的是base 26而不是base binary。
这不是乐趣结束的地方,我们在这个数字系统中没有零,因为 A 代表 1,B 代表 2,依此类推,Z 代表 26。
为了使问题易于理解,我们分两步解决问题:

  1. 考虑到系统中也有 0,将数字转换为以 26 为基数的表示。
  2. 将表示更改为系统中没有 0 的表示。

如何?这是一个例子

第1步:
考虑我们有数字 676,如何在 base 26 系统中获得它的表示?就像我们对二进制系统所做的那样,我们不是除以 2,而是除以 26。

Base 26 representation of 676 is : 100 

第2步
但是,嘿,我们的表示中不能有零。正确的?因为它不是我们数字系统的一部分。我们如何摆脱零?好吧,这很简单,但在此之前,让我们提醒一个简单的数学技巧:

Subtraction: 
5000 - 9, How do you subtract 9 from 0 ? You borrow
from next significant bit, right.  
  • 在处理零的十进制数系统中,我们借用 10 并从下一个有效值中减去 1。
  • 在 Base 26 Number System 中处理零,我们借用 26 并从下一个有效位中减去 1。

所以将 100 26转换为没有 '0' 的数字系统,我们得到 (25 26) 26
相同的符号表示为:YZ

这是相同的实现:

C++

#include 
using namespace std;
 
void printString(int n)
{
    int arr[10000];
    int i = 0;
 
    // Step 1: Converting to number assuming
    // 0 in number system
    while (n) {
        arr[i] = n % 26;
        n = n / 26;
        i++;
    }
 
    // Step 2: Getting rid of 0, as 0 is
    // not part of number system
    for (int j = 0; j < i - 1; j++) {
        if (arr[j] <= 0) {
            arr[j] += 26;
            arr[j + 1] = arr[j + 1] - 1;
        }
    }
 
    for (int j = i; j >= 0; j--) {
        if (arr[j] > 0)
            cout << char('A' + arr[j] - 1);
    }
 
    cout << endl;
}
 
// Driver program to test above function
int main()
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
    return 0;
}
 
// This code is contributed by Ankur Goel

Java

import java.util.*;
 
class GFG{
 
static void printString(int n)
{
    int []arr = new int[10000];
    int i = 0;
 
    // Step 1: Converting to number
    // assuming 0 in number system
    while (n > 0)
    {
        arr[i] = n % 26;
        n = n / 26;
        i++;
    }
 
    // Step 2: Getting rid of 0, as 0 is
    // not part of number system
    for(int j = 0; j < i - 1; j++)
    {
        if (arr[j] <= 0)
        {
            arr[j] += 26;
            arr[j + 1] = arr[j + 1] - 1;
        }
    }
 
    for(int j = i; j >= 0; j--)
    {
        if (arr[j] > 0)
            System.out.print(
                (char)('A' + arr[j] - 1));
    }
    System.out.println();
}
 
// Driver code
public static void main(String[] args)
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
}
}
 
// This code is contributed by amal kumar choubey

Python3

def printString(n):
     
    arr = [0] * 10000
    i = 0
 
    # Step 1: Converting to number
    # assuming 0 in number system
    while (n > 0):
        arr[i] = n % 26
        n = int(n // 26)
        i += 1
         
    #Step 2: Getting rid of 0, as 0 is
    # not part of number system
    for j in range(0, i - 1):
        if (arr[j] <= 0):
            arr[j] += 26
            arr[j + 1] = arr[j + 1] - 1
 
    for j in range(i, -1, -1):
        if (arr[j] > 0):
            print(chr(ord('A') +
                  (arr[j] - 1)), end = "");
 
    print();
 
# Driver code
if __name__ == '__main__':
     
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
 
# This code is contributed by Princi Singh

C#

using System;
class GFG{
 
static void printString(int n)
{
  int []arr = new int[10000];
  int i = 0;
 
  // Step 1: Converting to
  // number assuming 0 in
  // number system
  while (n > 0)
  {
    arr[i] = n % 26;
    n = n / 26;
    i++;
  }
 
  // Step 2: Getting rid of 0,
  // as 0 is not part of number
  // system
  for(int j = 0; j < i - 1; j++)
  {
    if (arr[j] <= 0)
    {
      arr[j] += 26;
      arr[j + 1] = arr[j + 1] - 1;
    }
  }
 
  for(int j = i; j >= 0; j--)
  {
    if (arr[j] > 0)
      Console.Write((char)('A' +
                     arr[j] - 1));
  }
  Console.WriteLine();
}
 
// Driver code
public static void Main(String[] args)
{
  printString(26);
  printString(51);
  printString(52);
  printString(80);
  printString(676);
  printString(702);
  printString(705);
}
}
 
// This code is contributed by 29AjayKumar

Javascript


输出
Z
AY
AZ
CB
YZ
ZZ
AAC

方法三:

我们可以使用递归函数,它肯定会减少时间并提高效率:

字母按顺序排列,例如:'ABCDEFGHIJKLMNOPQRSTUVWXYZ'。当您看到列和行编号是按字母顺序完成时,您在使用 excel 时体验过。

以下是我有目的地思考它的排列方式的逻辑。

(在数学术语中,[a , b ] 表示从 'a' 到 'b')。

[1,26] = [A,Z](理解为“1”代表“A”,“26”代表“Z”)。对于 [27,52] ,它将类似于 [AA,AZ],对于 [57,78] 它将是 [BA,BZ]

逻辑是在字母结束时按顺序附加一个字母,直到编号为 26。

例如,如果数字是“27”,大于“26”,那么我们只需除以26,余数为1,我们将“1”视为“A”,可以递归完成。

我们将为此使用Python ..

算法是:

1. 取一个数组,将字母从 A 到 Z 排序。(您也可以使用导入字符串和字符串函数来获取大写的“A 到 Z”。)

2.如果数字小于或等于'26',只需从数组中获取字母并打印它。

3.如果大于26,使用商余数规则,如果余数为零,有2种可能的方式,如果商为“1”,只需从索引[r-1]中哈希出字母('r'为余数) ,否则从 num =(q-1) 调用函数并在前面附加到索引 [r-1] 的字母。

4.如果余数不等于“0”,则调用 num = (q) 的函数并在前面追加到索引 [r-1] 的字母。

与此相关的代码是:

Python3

# Or you can simply take a string and perform this logic ,no issue i found in here.
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# defined a recursive function here.
# if number is less than "26", simply hash out (index-1)
# There are sub possibilities in possibilities,
# 1.if remainder is zero(if quotient is 1 or not 1) and
# 2. if remainder is not zero
 
def num_hash(num):
    if num < 26:
        return alpha[num-1]
    else:
        q, r = num//26, num % 26
        if r == 0:
            if q == 1:
                return alpha[r-1]
            else:
                return num_hash(q-1) + alpha[r-1]
        else:
            return num_hash(q) + alpha[r-1]
 
 
# Calling the function out here and printing the ALphabets
# This code is robust ,work for any positive integer only.
# You can try as much as you want
print(num_hash(26))
print(num_hash(51))
print(num_hash(52))
print(num_hash(80))
print(num_hash(676))
print(num_hash(702))
print(num_hash(705))
输出
Z
AY
AZ
CB
YZ
ZZ
AAC