作为一名伪程序员,为了提高自身内功修养,选择leetcode这个不错的平台静心刷题,研究算法。写博客,一方面可以让自己的只是沉淀一下,另一方面激励自己不断的前进。
下面贴上自己Accept的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* helper(int num) {
char* first[]={ ""," One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine" };
char* second[]= { " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" };
char* third[]= { "", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" };
char s[64]={0};
int hundred=num/100;
num=num%100;
int tenth=num/10;
int single=num%10; // printf("%d %d %d\n",hundred,tenth,single);
if(hundred)
{
strcpy(s,first[hundred]);
strcpy(s+strlen(s)," Hundred");
}
if(tenth)
{
if(tenth==1)
{
strcpy(s+strlen(s),second[single]);
return s;
}
else
strcpy(s+strlen(s),third[tenth]);
}
if(single)
{
strcpy(s+strlen(s),first[single]);
}
//printf("%s\n",s);
return s;
}
char* numberToWords(int num) {
char* unit[]={""," Thousand"," Million"," Billion"," Trillion"};
int part[5]={0};//定义字符数组一定要赋初值,否则会出现意外的错误
char s[1000]={0};
char temp[1000]={0};
if(num==0) strcpy(s," Zero");
else{
for(int i=0;i<5;i++)
{
part[i]=num%1000;
num/=1000;printf("%d\n",part[i]);
}
for(int i=0;i<5;i++)
{
memset(temp,0,sizeof(temp));
if(part[i]==0)continue;
strcpy(temp+strlen(temp),helper(part[i]));
strcpy(temp+strlen(temp),unit[i]);
strcpy(temp+strlen(temp),s);
strcpy(s,temp);
}
}
return s+1;//+1是为了去掉第一个空格
}总结:写代码,思路首先要明确;写的代码只是按照自己的思路实现而已。当出现错误时,要冷静,慢慢排查。
LeetCode题解与心得
959

被折叠的 条评论
为什么被折叠?



