168 excel sheet column title

Описание

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

For example:

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

2. Анализ

3. Код один

class Solution {
public:
    string convertToTitle(int n) {
        if (n <= 0) return "";
        string title = "";
        while (n > 26) {
            unsigned int remaind = n % 26;
            title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
            n /= 26;
            n -= remaind > 0 ? 0 : 1;
        }
        unsigned int remaind = n % 26;
        title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
        return title;
    }
};

4. Код 2.

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

Permalink

Cannot retrieve contributors at this time

168. Excel Sheet Column Title

  • Difficulty: Easy.
  • Related Topics: Math.
  • Similar Questions: Excel Sheet Column Number.

Problem

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

For example:

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

Example 1:

Example 2:

Example 3:

Solution

/**
 * @param {number} n
 * @return {string}
 */
var convertToTitle = function(n) {
  var num = n;
  var tmp = 0;
  var res = '';
  while (num > 0) {
    tmp = num % 26;
    if (tmp === 0) tmp = 26;
    res = getChar(tmp) + res;
    num = (num - tmp) / 26;
  }
  return res;
};

var getChar = function (num) {
  var start = 'A'.charCodeAt(0);
  return String.fromCharCode(start + num - 1);
};

Explain:

nope.

Complexity:

  • Time complexity : O(log(n)).
  • Space complexity : O(1).

Содержание

  1. 168 excel sheet column title
  2. Intelligent Recommendation
  3. [leetcode] 168. Excel Sheet Column Title
  4. Leetcode 168. Excel Sheet Column Title 26
  5. LeetCode-168. Excel Sheet Column Title
  6. LeetCode notes: 168. Excel Sheet Column Title
  7. leetcode(168) —— Excel Sheet Column Title
  8. More Recommendation
  9. 【leetcode】168(Easy). Excel Sheet Column Title
  10. leetcode-168-Excel Sheet Column Title
  11. LeetCode:168. Excel Sheet Column Title
  12. [LeetCode]—168. Excel Sheet Column Title
  13. 168 excel sheet column title
  14. topic
  15. Example 1:
  16. Example 2:
  17. Example 3:
  18. answer
  19. Intelligent Recommendation
  20. [LeetCode]—168. Excel Sheet Column Title
  21. [leetcode]168. Excel Sheet Column Title
  22. leetcode: 168. Excel Sheet Column Title
  23. leetcode of Excel Sheet Column Title (168)
  24. Java for LeetCode 168 Excel Sheet Column Title
  25. 168. Excel Sheet Column Title
  26. topic
  27. Example 1:
  28. Example 2:
  29. Example 3:
  30. algorithm
  31. Intelligent Recommendation
  32. [LeetCode]—168. Excel Sheet Column Title
  33. [leetcode]168. Excel Sheet Column Title
  34. leetcode: 168. Excel Sheet Column Title
  35. leetcode of Excel Sheet Column Title (168)
  36. Java for LeetCode 168 Excel Sheet Column Title
  37. Русские Блоги
  38. Leetcode 168. Excel Sheet Column Title
  39. Интеллектуальная рекомендация
  40. Проверка полномочий на основе JWT и фактические боевые учения
  41. [Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов
  42. Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)
  43. [Серия исходного кода Java] строка (2) Проблема нового, а не новой
  44. 05-Vue News Mobile Project
  45. Вам также может понравиться
  46. 1008 Рассматривая задача Element Element Cycle (20 баллов)
  47. Linux centos7 виртуальная машина установить Docker (5) —. Netcore
  48. Разработать интерфейс мониторинга состояния здоровья
  49. [Реабилитация] #C Language Array Joseph Проблема
  50. Русские Блоги
  51. leetcode 168.Excel Sheet Column Title
  52. Excel Sheet Column Title
  53. Анализ: десятичное сокращение
  54. Интеллектуальная рекомендация
  55. Проверка полномочий на основе JWT и фактические боевые учения
  56. [Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов
  57. Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)
  58. [Серия исходного кода Java] строка (2) Проблема нового, а не новой
  59. 05-Vue News Mobile Project
  60. Вам также может понравиться
  61. 1008 Рассматривая задача Element Element Cycle (20 баллов)
  62. Linux centos7 виртуальная машина установить Docker (5) —. Netcore
  63. Разработать интерфейс мониторинга состояния здоровья
  64. [Реабилитация] #C Language Array Joseph Проблема

168 excel sheet column title

Description of the topic:

Given a positive integer, return the column name it corresponds to in the Excel table.

Example 1:

Example 2:

Example 3:

One line solution:

Intelligent Recommendation

[leetcode] 168. Excel Sheet Column Title

Description Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Example 2: Example 3: analysis The meaning of the title is: convert the.

Leetcode 168. Excel Sheet Column Title 26

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Example 2: Example 3: Topic link:https://leetcode.com/problems/excel-sheet-co.

LeetCode-168. Excel Sheet Column Title

168. Excel Sheet Column Title topic Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Input: 1 Output: “A” Example 2: Inp.

LeetCode notes: 168. Excel Sheet Column Title

problem: Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C . 26 -> Z 27 -> AA 28 -> AB main idea: Give .

leetcode(168) —— Excel Sheet Column Title

topic: Excel Sheet Column Title The topic is to ask for a positive integer, return the column name of the integer in excel, examples can be referred to the above figure, and so on. Answer question: Co.

More Recommendation

【leetcode】168(Easy). Excel Sheet Column Title

Solution ideas: Equivalent to decimal conversion to 26, is to control the remainder can not be 0 Submit code: operation result: Changed a bit, using StringBuilder: operation result: The discussion are.

leetcode-168-Excel Sheet Column Title

Error: cannot solve it. Pattern: which is the same as the normal integer divide, but we need minus one before. So stupid.

LeetCode:168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Example 2: Example 3: C++ code: .

[LeetCode]—168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Credits: Special thanks to @ifanchu for adding this problem and creating all test cases. Essen.

Источник

168 excel sheet column title

Decimal to 26
Note that z means 26 instead of 0

topic

Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C

26 -> Z
27 -> AA
28 -> AB

Example 1:

Input: 1
Output: “A”

Example 2:

Input: 28
Output: “AB”

Example 3:

Input: 701
Output: “ZY”

answer

Intelligent Recommendation

[LeetCode]—168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Credits: Special thanks to @ifanchu for adding this problem and creating all test cases. Essen.

[leetcode]168. Excel Sheet Column Title

leetcode: 168. Excel Sheet Column Title

168. Excel Sheet Column Title Description Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Input: 1 Output: «A» Example 2.

leetcode of Excel Sheet Column Title (168)

topic: Given a positive integer, it returns the name of the column corresponding to an Excel table. E.g, Example 1: Example 2: Example 3: python code: .

Java for LeetCode 168 Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C &.

Источник

168. Excel Sheet Column Title

topic

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

Example 1:

Input: 1
Output: “A”

Example 2:

Input: 28
Output: “AB”

Example 3:

Input: 701
Output: “ZY”

algorithm

There is still a difference between the traditional number and the algorithm for dividing each digit. The traditional numbers are 0, 1, 2, . 9, and then 10 instead of 11, and the letters are A, B, C. Z. , then AA, not BA, so this time each cycle is divided by 26 and then reduced by 1, that is i=i/26-1 This is the key to this algorithm. I didn’t find this feature when I was doing it, so it is especially complicated. If I am too troublesome, I will not paste it. I will compare it with a C language. Simple code.

Intelligent Recommendation

[LeetCode]—168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Credits: Special thanks to @ifanchu for adding this problem and creating all test cases. Essen.

[leetcode]168. Excel Sheet Column Title

leetcode: 168. Excel Sheet Column Title

168. Excel Sheet Column Title Description Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: Example 1: Input: 1 Output: «A» Example 2.

leetcode of Excel Sheet Column Title (168)

topic: Given a positive integer, it returns the name of the column corresponding to an Excel table. E.g, Example 1: Example 2: Example 3: python code: .

Java for LeetCode 168 Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C &.

Источник

Русские Блоги

Leetcode 168. Excel Sheet Column Title

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

Example 1:

Example 2:

Example 3:

Текущий остаток конвертируется в буквы, а частное -1 зацикливается.

Интеллектуальная рекомендация

Проверка полномочий на основе JWT и фактические боевые учения

Предисловие: Большинство систем, за исключением большинства финансовых систем, требуют строгой системы безопасности (такой как shiro), общие требования к безопасности системы не очень высоки, требуетс.

[Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов

1. Реализуйте переднюю и заднюю часть приложения Цель:Чтобы снять риск захвата интерфейса Android, сообщите пользователям, что приложение работает в фоновом режиме. Обычно нажимает клавишу Home, чтобы.

Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)

Эта статья основана на USB Wireless Network Card (RTL8188CUS Chip), приобретенной на определенном востоке, чтобы создать беспроводные горячие точки. Первоначально я хотел сделать один сценарий. Просто.

[Серия исходного кода Java] строка (2) Проблема нового, а не новой

Серия строк: 【Серия исходного кода Java】 строка (1) под анализом базовой структуры [Серия исходного кода Java] строка (2) Проблема нового, а не новой [Серия исходного кода Java] Строка (3) Общий анали.

05-Vue News Mobile Project

1 Javascri не добавляет при добавлении толстой кишки При получении и изменении атрибутов реквизит плюс this. $router.push( ) 2 Axios Установка и использование Цитата в main.js 2.1axios, чтобы отправит.

Вам также может понравиться

1008 Рассматривая задача Element Element Cycle (20 баллов)

Массив A содержит n (> 0) целое число, не позволяя использовать дополнительные массивы, чтобы повернуть каждое целое число в положение правого m (≥0), данные в (A 0) A1 ⋯ A N-1) (An-M ⋯ A N-1 A .

Linux centos7 виртуальная машина установить Docker (5) —. Netcore

Текущая версия: версия Docker (например, Docker 17.03.2) .netcore версия 3.1 1 Постройте зеркало 2 запустить зеркало 3 Доступ Введите контейнер Nginx: Посещение в контейнере Выйдите из контейнера, что.

Разработать интерфейс мониторинга состояния здоровья

1. Требование Интерфейс должен содержать логическую обработку и чтение базы данных. 2. Реализация 1) Разработать доступ к интерфейсу к базе данных, успешный доступ, код статуса возврата 200, ненормаль.

[Реабилитация] #C Language Array Joseph Проблема

Я не двигал код в течение года. Теперь мой мозг не хорош, я использовал глупость, чтобы решить проблему Йозефа кольца. Написание здесь является запись, которая спасает свой собственный беспорядок. Воп.

Источник

Русские Блоги

leetcode 168.Excel Sheet Column Title

Excel Sheet Column Title

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

1 -> A
2 -> B
3 -> C

26 -> Z
27 -> AA
28 -> AB

Анализ: десятичное сокращение

Интеллектуальная рекомендация

Проверка полномочий на основе JWT и фактические боевые учения

Предисловие: Большинство систем, за исключением большинства финансовых систем, требуют строгой системы безопасности (такой как shiro), общие требования к безопасности системы не очень высоки, требуетс.

[Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов

1. Реализуйте переднюю и заднюю часть приложения Цель:Чтобы снять риск захвата интерфейса Android, сообщите пользователям, что приложение работает в фоновом режиме. Обычно нажимает клавишу Home, чтобы.

Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)

Эта статья основана на USB Wireless Network Card (RTL8188CUS Chip), приобретенной на определенном востоке, чтобы создать беспроводные горячие точки. Первоначально я хотел сделать один сценарий. Просто.

[Серия исходного кода Java] строка (2) Проблема нового, а не новой

Серия строк: 【Серия исходного кода Java】 строка (1) под анализом базовой структуры [Серия исходного кода Java] строка (2) Проблема нового, а не новой [Серия исходного кода Java] Строка (3) Общий анали.

05-Vue News Mobile Project

1 Javascri не добавляет при добавлении толстой кишки При получении и изменении атрибутов реквизит плюс this. $router.push( ) 2 Axios Установка и использование Цитата в main.js 2.1axios, чтобы отправит.

Вам также может понравиться

1008 Рассматривая задача Element Element Cycle (20 баллов)

Массив A содержит n (> 0) целое число, не позволяя использовать дополнительные массивы, чтобы повернуть каждое целое число в положение правого m (≥0), данные в (A 0) A1 ⋯ A N-1) (An-M ⋯ A N-1 A .

Linux centos7 виртуальная машина установить Docker (5) —. Netcore

Текущая версия: версия Docker (например, Docker 17.03.2) .netcore версия 3.1 1 Постройте зеркало 2 запустить зеркало 3 Доступ Введите контейнер Nginx: Посещение в контейнере Выйдите из контейнера, что.

Разработать интерфейс мониторинга состояния здоровья

1. Требование Интерфейс должен содержать логическую обработку и чтение базы данных. 2. Реализация 1) Разработать доступ к интерфейсу к базе данных, успешный доступ, код статуса возврата 200, ненормаль.

[Реабилитация] #C Language Array Joseph Проблема

Я не двигал код в течение года. Теперь мой мозг не хорош, я использовал глупость, чтобы решить проблему Йозефа кольца. Написание здесь является запись, которая спасает свой собственный беспорядок. Воп.

Источник

[ ]:

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

For example:

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

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

[Violent solution]:

Time analysis:

Space Analysis:

[Optimized]:

Time analysis:

Space Analysis:

[Wonderful Output Condition]:

[Wonderful Corner Case]:

[Thinking problem]:

I don’t know how to separate the digits, I don’t think there is any more than one thing: all take out.eachOne, then get a reduction

[One sentence ideas]:

char ((n — 1) % 26 + ‘A’)Pay attentionLess1

[Input]: Empty: Normal situation: Extra big: Special: Special circumstances processed in the program: anomalies (illegal unreasonable input):

[Draw]:

[1 brush]:

  1. Pay attention to the number of new addsleftThen you need to write RES = New + Res.

[Two Brush]:

[Three brush]:

[Four brush]:

[Five brush]:

[Five minutes of naked eye debug results]:

[to sum up]:

Take outeachOne, then get a reduction

[Complexity]: Time Complexity: O (1) Space complexity: O(1)

[English data structure or algorithm, why not do other data structures or algorithms]:

[Key Template Code]:

ans = (char) ((n - 1) % 26 + 'A') + ans;

[Other Solution]:

[Follow Up]:

[Title changes to the LC]:

[Code style]:


class Solution {
    public String convertToTitle(int n) {
        String ans = "";
        while (n != 0) {
            ans = (char) ((n - 1) % 26 + 'A') + ans;
            n = (n - 1) / 26;
        }
        return ans;
    }
}

View Code

map<int, char> mapAlpha() {

string alphabet = «ABCDEFGHIJKLMNOPQRSTUVWXYZ»;

map<int, char> alphaInteger;

for (auto c : alphabet) {

alphaInteger[count % 26] = c;

int findMaxPower(int n) {

return count > 0 ? count : 0;

string convertToTitle(int n, map<int, char> &alphaMap) {

int max = findMaxPower(n);

int key = int(floor(n / pow(26, max))) % 26;

s += alphaMap.find(key)->second;

map<int, char> alphaMap = mapAlpha();

cout << convertToTitle(52, alphaMap) << endl;

for (int i = 0; i < 1000; i++) {

cout << convertToTitle(i, alphaMap) << » «;

Понравилась статья? Поделить с друзьями:
  • 16 ричные числа в excel
  • 16 ричная система счисления в excel
  • 16 разрядные числа в excel
  • 16 read and write the correct word next to numbers 1 6
  • 16 bit word address