zoukankan      html  css  js  c++  java
  • New Year and Old Property :dfs

    题目描述:

    Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.

    Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?

    Assume that all positive integers are always written without leading zeros.

    Input

    The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 1018) — the first year and the last year in Limak's interval respectively.

    Output

    Print one integer – the number of years Limak will count in his chosen interval.

    Sample test(s)

    input
    5 10
    output
    2
    input
    2015 2015
    output
    1
    input
    100 105
    output
    0
    input
    72057594000000000 72057595000000000
    output
    26

    Note

    In the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and1010 = 10102. Two of them (1012 and 1102) have the described property.

    题目大意:求a到b中包含的所有的整数二进制只有一个1的数的个数

    #include <bits/stdc++.h>
    using namespace std;
    long long num=0,a,b;
    void dfs(long long x,int y)//y代表x的二进制中有几个零
    {
     //   cout<<"x:"<<x<<"
    ";
        if(x>b)return;//如果超出范围,就返回
        else if(x>=a&&y==1)//如果在范围里 并且只有一个零 那个数就加一
          {
            num++;
          }
        if(y==0)dfs(x<<1,1);
        //如果是二进制里没有零的话(例:1111111),那么左移一位,最后一位就是零了
        //所以就直接dfs左移,然后y是1
        dfs((x<<1)+1,y);
        //除了零在最后还有 零在中间的
        //所以在上边基础上再加一  (例:10,左移一位加一:101)
    }
     
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
        cin>>a>>b;
        dfs(1,0);
        cout<<num<<endl;
        return 0;
    }
    

      

  • 相关阅读:
    使用ClassLoader加载配置文件
    Io流和Properties集合的联合应用
    文件拷贝案例
    倒计时
    静态代码块
    数组的四种排序(冒泡排序,选择排序,插入排序,快速排序)
    通过map集合统计每个字符出现的次数
    随机输入几个数字,删除重复数字(但要保留一个),留下不重复的数字
    流程图学习-1-基础符号
    Java-List的对象的校验不起作用的解决方案
  • 原文地址:https://www.cnblogs.com/52dxer/p/10407192.html
Copyright © 2011-2022 走看看