校招在線編程題,問題描述如下:
給定一個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;
}
}