小白笔记-------------------------leetcode(258. Add Digits )

本文介绍了一种将非负整数的所有位数相加直至结果为单一位数的算法实现,同时探讨了如何使用sprintf与sscanf函数进行数据格式化处理。

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] … );

参数列表

bufferchar型指针,指向将要写入的字符串的缓冲区。
format:格式化字符串。
[argument].. .:可选参数,可以是任何类型的数据。

返回值

返回写入buffer 的字符数,出错则返回-1. 如果 buffer 或 format 是空指针,且不出错而继续,函数将返回-1,并且 errno 会被设置为 EINVAL。
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;  
}    
          


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值