Digital Roots
来源:互联网 发布:网络直销是不是拉人的 编辑:程序博客网 时间:2024/06/03 15:59
Digital Roots
- 题目来源:[九度1124][1]
原始代码:
#include <stdio.h>int getsum(int a){ int ans=0; while (a!=0) { int i = a%10; a /= 10; ans += i; } return ans;}int main() { int a; while (scanf("%d", &a)!=EOF) { if (a==0) { break; } while (a>=10) { a = getsum(a); } printf("%d\n", a); } return 0;}
- 该代码提交时会一直报错:wrong answer
- 但是我自己输入时感觉都正确。那是什么原因呢?
- 原因:注意题目中:The integer may consist of a large number of digits.也就是说输入的数字可能非常大超过int所表示的范围。
解决办法:
- 不再用整数变量来保存输入的数字,再利用求模、求商等数学方法得到拆解后的数字。而是转而采用将输入数据当作字符串的技巧,直接将数字以字符串的形式保存起来,再依次遍历这个字符串,通过字符与字符’0’的ascii值的差,计算字符所表示的数字值。
- 以上方法见:王道机试指南p66
修改后代码:
#include <stdio.h>int getsum(int a){ int ans=0; while (a!=0) { int i = a%10; a /= 10; ans += i; } return ans;}int main() { char a[1000]; while (scanf("%s", a)!=EOF) {//利用字符串读入数字,作为字符串保存在内存中 int ans=0; //累加变量 for (int i=0; a[i]!=0; i++) { //遍历a中的每一个字符,直到a字符串结尾 ans += (a[i]-'0'); } if (ans==0) { break; } while (ans>=10) { ans = getsum(ans); } printf("%d\n", ans); } return 0;}
0 0
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- 欢迎使用CSDN-markdown编辑器
- Service的分类以及不同种类的服务在生命周期中如何执行
- SAP会计期间设置
- Parquet与ORC:高性能列式存储格式
- 设计模式-单例模式
- Digital Roots
- django1.10官方文档翻译
- 搭建一个免费的,无限流量的Blog----github Pages和Jekyll入门
- Ruby On Rails生成二维码
- 新的开始,新的征程!!
- 专注与游离,即为劳逸结合
- 51NOD 1049 最大子段和
- 集成学习---个体学习器的多样性
- 笔记:移动Web规范