[LeetCode-168] Excel Sheet Column Title(10进制转26进制)

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 

Excel序是这样的:A~Z, AA~ZZ, AAA~ZZZ, ……

本质上就是将一个10进制数转换为一个26进制的数

注意:由于下标从1开始而不是从0开始,因此要减一操作。

代码如下:

int convertToTitleLen(int n)
{
	if(n <= 0 ) {
		return 0;
	}
	
	int nCount = 0;
	
	while(n) {
		n = (n-1) / 26;	
		nCount ++;
	}
	
	return nCount;
}

char* convertToTitle(int n) 
{
	/*1.异常处理*/
    if(n <= 0 ) {
		return NULL;
	}
	int ntemp = 0;
	
	/*2.申请接收数组的空间*/
	int len = convertToTitleLen(n);
	char *convertToTitleArry = (char *)malloc(sizeof(char)*len+1);
	int nCount = 0;
	
	/*3.处理过程*/
	while(n) {
		ntemp = (n-1) % 26;
		
		convertToTitleArry[len-nCount-1] = 'A'+ntemp;
	
		n = (n-1)/26;
		nCount++;
	}
	convertToTitleArry[nCount] = '\0';
	
	return convertToTitleArry;	
}

完整代码如下:

// LeetCode168-Excel Sheet Column Title.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

int convertToTitleLen(int n)
{
	if(n <= 0 ) {
		return 0;
	}
	
	int nCount = 0;
	
	while(n) {
		n = (n-1)/ 26;	
		nCount ++;
	}
	
	return nCount;
}

char* convertToTitle(int n) 
{
	/*1.异常处理*/
    if(n <= 0 ) {
		return NULL;
	}
	int ntemp = 0;
	
	/*2.申请接收数组的空间*/
	int len = convertToTitleLen(n);
	char *convertToTitleArry = (char *)malloc(sizeof(char)*len+1);
	int nCount = 0;
	printf("[%d,len:%d]\n",__LINE__,len);
	/*3.处理过程*/
	while(n) {
		ntemp = (n-1) % 26;
		
		convertToTitleArry[len-nCount-1] = 'A'+ntemp;
	
		n = (n-1)/26;
		nCount++;
	}
	convertToTitleArry[nCount] = '\0';
	
	return convertToTitleArry;	
}


int main()
{
	int n = 0;
	char *convertToTitleArry;
	while(scanf("%d",&n)!=EOF) {
		convertToTitleArry = convertToTitle(n);
		printf("%s\n",convertToTitleArry);
	}
	return 0;
}



你可能感兴趣的:([LeetCode-168] Excel Sheet Column Title(10进制转26进制))