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

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

给定一个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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值