给定一个N,求1-N之间有多少可以输出的数。

时间:2023-01-09 09:34:14

校招在线编程题,问题描述如下:

给定一个N,求1-N之间有多少可以输出的数。

能输入的数:每一位是0或1的数
场景简述:小明向内存中,保存一些数字,但当从内存中读取时,只能读出部分数字。经过观察发现,这些数字中只包含0/1。当小明向内存中,保存1-n之间的数之后,有多少是可以打印的。 

import java.util.*;
//给定一个最大值,有多少个数能输出
//能输入的数:每一位是0或1的数
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int num=in.nextInt();
String str=String.valueOf(num);
int n= str.length();
int count=0;
//取得输入可能的范围[first]/(first-second)/[second-n位数最大值)
int first=(int)Math.pow(10, n-1);
int second=2*first;
//System.out.println("first:"+first+",second:"+second);
if(num==first){
count = countNum(first);
}else if(num>=second){
count = countNum(second);
}else{
count = countNum(first);
while(++first<=num){
if(isPrint(String.valueOf(first))){
count++;
}
}
}

System.out.println((int)count);
}
}
public static boolean isPrint(String str){
for(int i=0;i<str.length();i++){
//其中一位不为0或1,不参与计数
if(str.charAt(i)-'0'!=0 && str.charAt(i)-'0'!=1){
return false;
}
}
return true;
}
public static int countNum(int num){
String str=String.valueOf(num);
int n= str.length();
double count=0;
if(num==Math.pow(10,n-1))
count=Math.pow(2, n-1);
else count=Math.pow(2, n)-1;
return (int)count;
}
}