前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【刷题】Sum of Digits【1】

【刷题】Sum of Digits【1】

作者头像
司六米希
发布2022-11-15 19:22:21
3230
发布2022-11-15 19:22:21
举报
文章被收录于专栏:司六米希司六米希

【刷题】Sum of Digits【1】

一、题目

1.题目描述

题目:

在这里插入图片描述
在这里插入图片描述

输入

在这里插入图片描述
在这里插入图片描述

输出

在这里插入图片描述
在这里插入图片描述

示例 :

在这里插入图片描述
在这里插入图片描述

提示: In the first sample the number already is one-digit — Herald can’t cast a spell. The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once. The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

二、解题报告

1.思路分析

  • 不断对数字按位进行累加,直到变成一个数字为止

2.代码详解

python👇【检验超时】

代码语言:javascript
复制
a=input()
b=list(a)
c=[]
s=0
i=1
while 1:
    for j in range(len(b)):
        s+=int(b[j])
    if s==0:
        print(0)
        break
    if s<9:
        print(i)
        break
    else:
        b=list(str(s))
        c=[]
        s=0
        i+=1

C++👇

代码语言:javascript
复制
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include<set>
#include <algorithm>
using namespace std;
 
char s[100100];
 
int main() 
{
	int n,cnt,i,res;
	scanf("%s",s);
	cnt=0;
	while (s[1]) 
	{
		cnt++;
		res=0;
		for(i=0;s[i];i++)
		{
			res+=s[i]-'0';
		}
		sprintf(s,"%d",res);
	}
	printf("%d\n",cnt);
	return 0;
}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-06-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 【刷题】Sum of Digits【1】
  • 一、题目
    • 1.题目描述
    • 二、解题报告
      • 1.思路分析
        • 2.代码详解
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档