“求数字之和的三种算法”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“https://www.bilibili.com/video/BV1Ra4y1p7Si”的新页面) |
Jihongchang(讨论 | 贡献) (→第二种) |
||
(未显示同一用户的2个中间版本) | |||
第1行: | 第1行: | ||
https://www.bilibili.com/video/BV1Ra4y1p7Si | https://www.bilibili.com/video/BV1Ra4y1p7Si | ||
+ | |||
+ | === 题目 === | ||
+ | 例如:1234→1+2+3+4=10 | ||
+ | |||
+ | |||
+ | |||
+ | === 第一种 === | ||
+ | while 循环<syntaxhighlight lang="cpp"> | ||
+ | #include<stdio.h> | ||
+ | |||
+ | int f(int n) | ||
+ | { | ||
+ | int ret = 0; | ||
+ | while (n > 0) | ||
+ | { | ||
+ | ret = ret + (n % 10); | ||
+ | n = n / 10; | ||
+ | } | ||
+ | return ret; | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | int a = 1234; | ||
+ | int ret = f(a); | ||
+ | printf("ret = %d \n", ret); | ||
+ | return 0; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | === 第二种 === | ||
+ | 递归<syntaxhighlight lang="cpp"> | ||
+ | #include<stdio.h> | ||
+ | |||
+ | int f(int n) | ||
+ | { | ||
+ | if (n == 0) { | ||
+ | return 0; | ||
+ | } | ||
+ | return n % 10 + f(n / 10); | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | int a = 1234; | ||
+ | int ret = f(a); | ||
+ | printf("ret = %d \n", ret); | ||
+ | return 0; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | === 第三种 === | ||
+ | 整型转字符串,然后遍历字符转整型相加<syntaxhighlight lang="c"> | ||
+ | #define _CRT_SECURE_NO_WARNINGS 1 | ||
+ | |||
+ | #include<stdio.h> | ||
+ | #include <stdlib.h> | ||
+ | |||
+ | int f(int n) | ||
+ | { | ||
+ | int ret = 0; | ||
+ | char string[16] = { 0 }; | ||
+ | _itoa(n, string, 10); | ||
+ | printf("数字:%d 转换后的字符串为:%s\n", n, string); | ||
+ | |||
+ | int i = 0; | ||
+ | while (string[i] != '\0') | ||
+ | { | ||
+ | ret += string[i] - '0'; | ||
+ | i++; | ||
+ | } | ||
+ | return ret; | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | int a = 1234; | ||
+ | int ret = f(a); | ||
+ | printf("ret = %d \n", ret); | ||
+ | return 0; | ||
+ | } | ||
+ | </syntaxhighlight> |
2022年11月9日 (三) 06:59的最新版本
https://www.bilibili.com/video/BV1Ra4y1p7Si
题目
例如:1234→1+2+3+4=10
第一种
while 循环
#include<stdio.h>
int f(int n)
{
int ret = 0;
while (n > 0)
{
ret = ret + (n % 10);
n = n / 10;
}
return ret;
}
int main() {
int a = 1234;
int ret = f(a);
printf("ret = %d \n", ret);
return 0;
}
第二种
递归
#include<stdio.h>
int f(int n)
{
if (n == 0) {
return 0;
}
return n % 10 + f(n / 10);
}
int main() {
int a = 1234;
int ret = f(a);
printf("ret = %d \n", ret);
return 0;
}
第三种
整型转字符串,然后遍历字符转整型相加
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdlib.h>
int f(int n)
{
int ret = 0;
char string[16] = { 0 };
_itoa(n, string, 10);
printf("数字:%d 转换后的字符串为:%s\n", n, string);
int i = 0;
while (string[i] != '\0')
{
ret += string[i] - '0';
i++;
}
return ret;
}
int main() {
int a = 1234;
int ret = f(a);
printf("ret = %d \n", ret);
return 0;
}