AcWing第 31 场周赛——01数

题目描述

如果一个正整数,其各个数位上的数字均满足要么是 0,要么是 1,则称该数字为 01数。

例如,1和 10 都是 01数。

给定一个整数 n。请你计算,1∼n中有多少个 01数。

输入格式

一行,一个整数 n。

输出格式

一个整数,表示 01数的数量。

数据范围

前六个测试点满足 1≤n≤100。
所有测试点满足 1≤n≤109。

输入样例:

10

输出样例:

2

示例代码

复制代码
 1 import java.util.*;
 2 
 3 public class Main {
 4     
 5     private static int res = 0;
 6     
 7     private static int n;
 8     
 9     private static int[] val = new int[10];
10     
11     private static int[] visit = new int[10];
12     
13     public static void main(String[] args) {
14         Scanner input = new Scanner(System.in);
15         n = input.nextInt();
16         int len = String.valueOf(n).length();
17         recursion(len, 1);
18         System.out.println(res);
19     }
20     
21     public static void recursion(int len, int pos) {
22         if (pos > len) {
23             int total = 0;
24             for (int i = 1; i <= len; i++) {
25                 if (val[i - 1] == 1) {
26                     total += Math.pow(10, len - i);
27                 }
28             }
29             if (total >= 1 && total <= n) {
30                 res++;
31             }
32             return;
33         }
34         
35         for (int i = 0; i <= 1; i++) {
36             if (visit[pos - 1] == 0) {
37                 // 标记
38                 visit[pos - 1] = 1;
39                 val[pos - 1] = i;
40                 // 递归
41                 recursion(len, pos + 1);
42                 // 清除
43                 visit[pos - 1] = 0;
44             }
45         }
46     }
47 }
复制代码

DFS优雅实现

复制代码
import java.util.*;

public class Main {
    
    private static int res = 0;
    
    private static int n;
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        n = input.nextInt();
        dfs(1);
        System.out.println(res);
    }
    
    public static void dfs(int val) {
        if (val > n) {
            return;
        }
        res++;
        // 填1
        dfs(10 * val + 1);
        // 填0
        dfs(10 * val);
    }
}
复制代码

 

posted @   没有你哪有我  阅读(58)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示