leetcode刷题-Integer to English Words

作为一名伪程序员,为了提高自身内功修养,选择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是为了去掉第一个空格
}

总结:写代码,思路首先要明确;写的代码只是按照自己的思路实现而已。当出现错误时,要冷静,慢慢排查。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值