📌  相关文章
📜  计数数字以二进制表示形式全为1

📅  最后修改于: 2021-05-07 05:41:01             🧑  作者: Mango

给定整数n ,任务是计算小于或等于n的总幸运数。如果数字从一开始就具有二进制形式的全部1传染性数字,那么它就是幸运的。例如,1、3、7、15是幸运数字,而2、5和9不是幸运数字。
例子:

Input :n = 7 
Output :3
1, 3 and 7 are lucky numbers

Input :n = 17
Output :4

方法:一种方法是,首先,我们找出每一个数字,比检查1对每个号码的传染性数的二进制表示,但这种方法非常耗时,而且可以给TLE如果约束是两个大的,高效的方法可以找到通过观察这些数字,我们可以说每个ith幸运数字都可以通过公式2 i -1找到,并且通过迭代一个循环直到小于等于n的数字,我们可以找到总的幸运数字。
下面是上述方法的实现

CPP
#include 
using namespace std;
 
int countLuckyNum(int n)
{
    int count = 0, i = 1;
 
    while (1) {
        if (n >= ((1 << i) - 1))
            count++;
        else
            break;
        i++;
    }
 
    return count;
}
 
// Driver code
int main()
{
    int n = 7;
    cout << countLuckyNum(n);
    return 0;
}


Java
import java.util.*;
import java.lang.*;
import java.io.*;
 
public class GFG {
 
    // Function to return the count of lucky number
    static int countLuckyNum(int n)
    {
 
        int count = 0, i = 1;
        while (true) {
            if (n >= ((1 << i) - 1))
                count++;
            else
                break;
            i++;
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 7;
        System.out.println(countLuckyNum(n));
    }
}


Python
# python3 code of above problem
 
# function to count the lucky number
 
def countLuckyNum(n):
     
    count, i = 0, 1
     
    while True:
        if n>= 2**i-1:
            count+= 1
        else:
            break
        i+= 1;
    return count    
 
# driver code
n = 7
 
print(countLuckyNum(n))


C#
// C# implementation of the approach
using System;
 
public class GFG {
 
    // Function to return the count of lucky number
    static int countLuckyNum(int n)
    {
 
        int count = 0, i = 1;
        while (true) {
            if (n >= ((1 << i) - 1))
                count++;
            else
                break;
            i++;
        }
        return count;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 7;
        Console.WriteLine(countLuckyNum(n));
    }
}


PHP
= ((1 << $i) - 1))
        $count += 1;
      else
        break;
      $i += 1;
  }
  return $count;                    
}  
     
// Driver code  
$n = 7;
echo countLuckyNum($n) ;  
?>


Javascript


output:3