📌  相关文章
📜  检查数字是否仅设置了第一位和最后一位套装2

📅  最后修改于: 2021-05-25 01:57:36             🧑  作者: Mango

给定正整数n,请检查在n的二进制表示形式中是否仅设置了第一位和最后一位。打印“是”或“否”。
例子:

我们已经在这里讨论了一个解决方案。
在这篇文章中,讨论了一个更简单的解决方案。

C++
// C++ to check whether the number has only
// first and last bits set
#include 
using namespace std;
 
// function to check whether the number has only
// first and last bits set
bool onlyFirstAndLastAreSet(unsigned int n)
{
    if (n == 1)
        return true;
    if (n == 2)
        return false;
    return (((n - 1) & (n - 2)) == 0);
}
 
// Driver program to test above
int main()
{
    unsigned int n = 9;
    if (onlyFirstAndLastAreSet(n))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java to check whether
// the number has only
// first and last bits set
 
class GFG
{
// function to check whether
// the number has only
// first and last bits set
static boolean onlyFirstAndLastAreSet(int n)
{
    if (n == 1)
        return true;
    if (n == 2)
        return false;
    return (((n - 1) &
             (n - 2)) == 0);
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 9;
    if (onlyFirstAndLastAreSet(n))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed
// by Smitha


Python3
# Python 3 to check whether
# the number has only
# first and last bits set
 
# function to check whether
# the number has only
# first and last bits set
def onlyFirstAndLastAreSet(n):
 
    if (n == 1):
        return True
    if (n == 2):
        return False
 
    return (((n - 1) &
             (n - 2)) == 0)
 
# Driver Code
n = 9
if (onlyFirstAndLastAreSet(n)):
    print("Yes")
else:
    print("No")
     
# This code is contributed
# by Smitha


C#
// C# to check whether
// the number has only
// first and last bits set
using System;
 
class GFG
{
// function to check whether
// the number has only
// first and last bits set
static bool onlyFirstAndLastAreSet(int n)
{
    if (n == 1)
        return true;
    if (n == 2)
        return false;
    return (((n - 1) &
             (n - 2)) == 0);
}
 
// Driver Code
public static void Main()
{
    int n = 9;
    if (onlyFirstAndLastAreSet(n))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed
// by Smitha


PHP


Javascript


输出:
Yes