C语言之宝宝会数数

欢迎进入我的C语言世界

题目

Problem Description

光头强的儿子名字叫宝宝强,天生就会数数!
在这里插入图片描述

他从0开始数,一直数到n,然后这些数字排成一行,用火柴棒一笔一笔的摆出来,如图所示。现在给定n,光头强想要知道最少需要多少根火柴棒,才能够宝宝强数到n。

Input

多组测试数据。

输入第一行为正整数n(n≤10^5),表示宝宝强要从0数到的数。

Output

输出1个正整数,表示火柴棒根数。

Sample Input

2

Sample Output

13

答案

下面展示 实现代码

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
long long int num[1000000];
int main()
{
    
    
	int n,cnt;
	int i = 0, j = 0, k, t ,w;
	while(scanf("%d",&n) != EOF)
	{
    
    
		cnt = 0;
		i = 0, j = 0;
		for(k = 0; k <= n; k++)
		{
    
    
			if(k < 10)
			{
    
    
				num[i] = k;
				i++;		
			}
			else
			{
    
    		
				t = k;
				for(w = i ; t >= 10; w ++)
				{
    
     
					num[w]= t % 10;
					t = t / 10;
					if(t < 10)
					{
    
    
						num[++w] = t;				
					}
				} 
				i = w;
			}
		}
		for(j = 0; j < i; j ++)
		{
    
    
			if(num[j] == 1)
			{
    
    
				cnt = cnt + 2;
			}
			else if(num[j] == 0 || num[j] == 6 || num[j] == 9)
			{
    
    
				cnt = cnt + 6;
			}
			else if(num[j] == 2 || num[j] == 3 || num[j] == 5)
			{
    
    
				cnt = cnt + 5;
			}
			else if(num[j] == 4)
			{
    
    
				cnt = cnt + 4;
			}
			else if(num[j] == 7)
			{
    
    
				cnt = cnt + 3;
			}
			else if(num[j] == 8)
			{
    
    
				cnt = cnt + 7;
			}
		}	
		cout << cnt << endl;
	}
	return 0;
}

本题感悟

本块内容可能来自课本或其他网站,若涉及侵权问题,请联系我进行删除,谢谢大家啦~

本题一开始做的时候思路就是这个,但是没有考虑到10以后的情况,对++w理解错误,导致WA

猜你喜欢

转载自blog.csdn.net/hongguoya/article/details/105559547