Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
自己寻思了半天,结果发现别人的直接两行出来,惊叹之余,果断用了别人的方法,在这里总结两个函数
1、sprintf
功能
头文件
原型
int sprintf( char *buffer, const char *format, [ argument] … );
参数列表
buffer:
char型指针,指向将要写入的字符串的缓冲区。
format:格式化字符串。
[argument]..
.:可选参数,可以是任何类型的数据。
返回值
返回写入buffer 的字符数,出错则返回-1. 如果 buffer 或 format 是空指针,且不出错而继续,函数将返回-1,并且 errno 会被设置为 EINVAL。
2、sscanf
代码如下:
2、sscanf
函数原型:
int sscanf( const
char *, const char *, ...);
int sscanf(const char *buffer,const char *format,[argument ]...);
buffer存储的数据
format格式控制字符串
argument 选择性设定字符串
sscanf会从buffer里读进数据,依照format的格式将数据写入到argument里。
头文件
编辑
#include<stdio.h> 或者
#include <cstdio>
返回值
编辑
成功则返回参数数目,失败则返回-1,错误原因存于
errno中。
经多次测试[来源请求],在linux系统中成功返回的是成功转换的值的个数,例如:
sscanf("1 2 3","%d %d %d",buf1, buf2, buf3); 成功调用返回值为3,即buf1,buf2,buf3均成功转换。
sscanf("1 2","%d %d %d",buf1, buf2, buf3); 成功调用返回值为2,即只有buf1,buf2成功转换。
int addDigits(int num) {
while(num>=10){
num = (num/10)+num%10;
}
return num;
}
本文介绍了一种将非负整数的所有位数相加直至结果为单一位数的算法实现,同时探讨了如何使用sprintf与sscanf函数进行数据格式化处理。
713

被折叠的 条评论
为什么被折叠?



