zoj 1115 Digital Roots
2014-12-25 14:25
267 查看
正确代码:
分析:
如此简单的一道题我写得却很纠结,因为对int和char之间的转换不熟悉。代码写得也比较乱,还有重复的一个while循环,应该可以简化的。
还可以简化 if(strcmp(num.c_str(),"0")!=0)
成为 while(cin >> num && strcmp(num.c_str(),"0")!=0)
itoa函数只能在vc下使用,它不是一个标准的库函数。不要用它了,使用<stdio.h>下的sprintf,功能相同也更好用。
c++ string类型在使用字符串函数时不同于char*,它需要把“变量名”换成“变量名.c_str()”。例如num换成num.c_str()
c++ string类型在使用springf时要把变量名换成&num[0]。
另外注意,把char型数字传给int型的简单方法 res+=num[i]-'0';
#include <iostream> #include <stdio.h> #include <string.h> //#include <stdlib.h> using namespace std; int main(int argc, char *argv[]) { string num; while(cin >> num ){ if(strcmp(num.c_str(),"0")!=0){ int res=0,i=0; while(num[i]!='\0'){ res+=num[i]-'0'; i++; } while(res>=10){ //itoa(res,&num[0],10); sprintf(&num[0],"%d",res); i=0; res=0; while(num[i]!='\0'){ res+=num[i]-'0'; i++; } } cout << res << endl; } else break; } return 0; }
分析:
如此简单的一道题我写得却很纠结,因为对int和char之间的转换不熟悉。代码写得也比较乱,还有重复的一个while循环,应该可以简化的。
还可以简化 if(strcmp(num.c_str(),"0")!=0)
成为 while(cin >> num && strcmp(num.c_str(),"0")!=0)
itoa函数只能在vc下使用,它不是一个标准的库函数。不要用它了,使用<stdio.h>下的sprintf,功能相同也更好用。
c++ string类型在使用字符串函数时不同于char*,它需要把“变量名”换成“变量名.c_str()”。例如num换成num.c_str()
c++ string类型在使用springf时要把变量名换成&num[0]。
另外注意,把char型数字传给int型的简单方法 res+=num[i]-'0';
相关文章推荐
- ZOJ Problem Set - 1115 Digital Roots
- ZOJ 1115 Digital Roots 水题
- ZOJ 1115 Digital Roots
- 数根计算ZOJ 1115 Digital Roots
- zoj 1115 Digital Roots
- ZOJ Problem Set - 1115||Digital Roots
- ZOJ_1115_Digital Roots
- ZOJ 1115-Digital Roots
- ZOJ 1115 Digital Roots
- zoj1115-Digital Roots
- zoj 1115 Digital Roots
- zoj1115 Digital Roots
- zoj 1115 Digital Roots
- ZOJ Problem 1115 Digital Roots
- php - zoj 1115 Digital Roots
- ZOJ 1115 Digital Roots
- ZOJ 1115 Digital Roots(简单,字符串与数)
- ZOJ Problem Set - 1115 Digital Roots
- zoj 1115 Digital Roots
- ZOJ 1115 Digital Roots