U587858题解
你可绝对要看完在这篇文章啊,求求你了 ( ・´ω`・ )
一、题目分析
本题要求计算一个非负整数的位数,属于数字处理的入门题。核心考察对数字分解或字符串转换的掌握,需特别注意特殊值 的处理(规定为 位数)。
- 输入:非负整数 n(范围 ,最大为 位数)。
- 输出:该数字包含的数字个数(如 是 位数, 是 位数)。
二、解题思路
.核心方法:有两种常见思路:
数字分解法:通过循环除以 ,统计除法次数(直到商为 ),次数即为位数(注意 的特殊处理)。 字符串转换法:将数字转换为字符串,直接获取字符串的长度( 转换后长度为 ,符合要求)。
.特殊情况处理:
- 当 时,直接返回 (无需循环或转换后判断)。
- 当 时,两种方法均可正常计算。
三、代码实现(多语言示例)
1. Python 代码1(字符串转换法)
n = int(input())
# 转换为字符串后取长度
print(len(str(n)))2. Python 代码2(数字分解法)
n = int(input())
if n == 0:
print(1)
else:
count = 0
while n > 0:
n = n // 10 # 除以10取整
count += 1
print(count)3. C++ 代码1(数字分解法)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if (n == 0) {
cout << 1 << endl;
return 0;
}
int count = 0;
while (n > 0) {
n /= 10; // 等价于 n = n / 10
count++;
}
cout << count << endl;
return 0;
}4. C++ 代码2 (字符串输出法)
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s; //建一个字符串变量输入然后直接输出长度
cout << s.size();
return 0;
}5. Java 代码(字符串转换法)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// 转换为字符串后获取长度
System.out.println(String.valueOf(n).length());
}
}6. C 代码(数字分解法)
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
if (n == 0) {
printf("1\n");
return 0;
}
int count = 0;
while (n > 0) {
n /= 10;
count++;
}
printf("%d\n", count);
return 0;
}