Algorithm_Number of Digit One(1的数目)

这篇博客探讨了如何计算在给定整数范围内数字1出现的次数,提供了两种不同的解题思路和方法。

题目:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

给定一个整数n,计算所有小于等于n的非负整数中数字1出现的次数。

例如:

给定 n = 13,

返回6, 因为数字1在下面的数字中出现:1, 10, 11, 12, 13(共6次)。

解法一:

package com.liangdianshui;

import java.util.Scanner;

public class algorithm1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long value = scanner.nextLong();
        long startTime = System.currentTimeMillis();
        String valueOf = String.valueOf(CountOne(value));
        long endTime = System.currentTimeMillis();
        long time = endTime - startTime;
        System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
    }

    public static long CountOne(long n) {
        long count = 0, i = 0, j = 1;
        for (i = 0; i <=n; i++) {
            j = i;
            while (j != 0) {
                if (j % 10 == 1) {
                    count++;
                }
                j /= 10;
            }
        }
        return count;
    }
}


解法二:

package com.liangdianshui;

import java.util.Scanner;

public class algorithm2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long value = scanner.nextLong();
        long startTime = System.currentTimeMillis();
        String valueOf = String.valueOf(CountOne(value));
        long endTime = System.currentTimeMillis();
        long time = endTime - startTime;
        System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
    }

    public static long CountOne(long n) {
        long count = 0;
        if (n == 0)
            count = 0;
        else if (n > 1 && n < 10)
            count = 1;
        else {
            long highest = n;// 最高位的数字
            int bit = 0;
            while (highest >= 10) {
                highest = highest / 10;
                bit++;
            }

            int weight = (int) Math.pow(10, bit);// 最高位的权重,即最高位一个1代表的大小
            if (highest == 1) {
                count = CountOne(weight - 1) + CountOne(n - weight) + n
                        - weight + 1;
            } else {
                count = highest * CountOne(weight - 1)
                        + CountOne(n - highest * weight) + weight;
            }
        }
        return count;
    }
}

解法三:

package com.liangdianshui;

import java.util.Scanner;

public class algorithm3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long value = scanner.nextLong();
        long startTime = System.currentTimeMillis();
        String valueOf = String.valueOf(CountOne(value));
        long endTime = System.currentTimeMillis();
        long time = endTime - startTime;
        System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
    }

    public static long CountOne(long n) {
        long count = 0;
        long i = 1;
        long current = 0, after = 0, before = 0;
        while ((n / i) != 0) {
            current = (n / i) % 10;
            before = n / (i * 10);
            after = n - (n / i) * i;

            if (current > 1)
                count = count + (before + 1) * i;
            else if (current == 0)
                count = count + before * i;
            else if (current == 1)
                count = count + before * i + after + 1;

            i = i * 10;
        }
        return count;

    }
}


这段代码使用了 Python 的 `subprocess` 模块来执行一个外部命令,具体是运行名为 `c.exe` 的可执行文件,并传递一个参数 `algorithm_number`。下面是对这行代码的详细解析: ```python result = subprocess.check_output( ['c.exe', str(algorithm_number)], stderr=subprocess.STDOUT, universal_newlines=True ) ``` ### 参数说明 1. **`['c.exe', str(algorithm_number)]`** - 这是一个命令列表,表示要执行的命令和参数。 - `'c.exe'` 是要执行的程序名称(Windows 下的可执行文件)。 - `str(algorithm_number)` 将变量 `algorithm_number` 转换为字符串形式作为参数传入到 `c.exe` 中。 - 例如:如果 `algorithm_number` 是 `2`,那么这条命令就相当于在命令行中执行: ```bash c.exe 2 ``` 2. **`stderr=subprocess.STDOUT`** - 这个参数将标准错误流 (`stderr`) 合并到标准输出流 (`stdout`)。 - 这样做可以让 `check_output` 函数同时捕获正常输出和错误信息。 3. **`universal_newlines=True`** - 这个参数确保输出结果是以字符串形式返回而不是字节流(即 `str` 类型而非 `bytes` 类型)。 - 如果不设置这个参数,默认情况下 `check_output` 返回的是 `bytes` 类型的数据。 ### 返回值 - `result` 变量会存储 `c.exe` 执行后的输出结果(包括标准输出和标准错误),并且由于设置了 `universal_newlines=True`,它将以字符串形式呈现。 --- ### 示例完整代码 ```python import subprocess algorithm_number = 1 try: result = subprocess.check_output( ['c.exe', str(algorithm_number)], stderr=subprocess.STDOUT, universal_newlines=True ) print("执行结果:") print(result) except subprocess.CalledProcessError as e: print(f"命令执行失败,返回码 {e.returncode}") print("错误输出:") print(e.output) ``` ### 异常处理说明 - `subprocess.check_output` 在命令执行失败(即返回码非零)时会抛出 `subprocess.CalledProcessError` 异常。 - 因此建议用 `try-except` 包裹以进行异常处理。 --- ### 相关问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值