跳到正文

个人记录

U587858题解

LaoshuLaohu约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月16日
篇幅
约 4 分钟

版本

  1. v1当前

U587858题解

你可绝对要看完在这篇文章啊,求求你了 ( ・´ω`・ )

一、题目分析

本题要求计算一个非负整数的位数,属于数字处理的入门题。核心考察对数字分解或字符串转换的掌握,需特别注意特殊值 “0”“0” 的处理(规定为 11 位数)。

  • 输入:非负整数 n(范围 (0≤n≤106)(0≤n ≤10^6),最大为 1010 位数)。
  • 输出:该数字包含的数字个数(如 123123 是 33 位数,00 是 11 位数)。

二、解题思路

11.核心方法:有两种常见思路:

数字分解法:通过循环除以 1010,统计除法次数(直到商为 00),次数即为位数(注意 00 的特殊处理)。 字符串转换法:将数字转换为字符串,直接获取字符串的长度(00 转换后长度为 11,符合要求)。

22.特殊情况处理:

  • 当 n=0n = 0 时,直接返回 11(无需循环或转换后判断)。
  • 当 n≥1n ≥ 1 时,两种方法均可正常计算。

三、代码实现(多语言示例)

1. Python 代码1(字符串转换法)

Python
n = int(input())
# 转换为字符串后取长度
print(len(str(n)))

2. Python 代码2(数字分解法)

Python
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(数字分解法)

C++
#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 (字符串输出法)

C++
#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    cin >> s;  //建一个字符串变量输入然后直接输出长度
    cout << s.size();
    return 0;
}

5. Java 代码(字符串转换法)

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 代码(数字分解法)

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;
}
能动动你的小鼠标点个赞吗~
原文