📜  用于替换固定大小小于 64 的布尔数组的位操作技术

📅  最后修改于: 2022-05-13 01:56:05.521000             🧑  作者: Mango

用于替换固定大小小于 64 的布尔数组的位操作技术

空间复杂度是程序员最低估的资产。提交解决方案时几乎看不到内存限制超出 (MLE)。但是,节省内存是程序员应该关心的最重要的事情。如果需要为用户创建应用程序,则应尽可能提高内存效率。
布尔数组已被用作解决不同问题的容器。本文重点讨论布尔数组的替代方案。

整数变量作为容器

通常,Integer 变量有 4 个字节(考虑到 C++),因此有 32 个布尔位来表示一个数字。例如,要表示 10,布尔位可以写成:

这意味着可以将这些位用作大小为 32 的布尔数组中的布尔值。如果需要,可以使用 64 位整数来增加大小。

如何使用整数变量作为容器?

让我们详细讨论如何将 Integer 变量用作容器。

第一步是将整数变量初始化为 0,以获得大小为 32 的布尔容器,其中所有位最初为 false。

设置一点为真:
使用 AND、NOT、OR 和 SHIFT运算符运算符等按位运算符,将任何所需位置的任何位设置为 true。例如,在位置 7- 处设置一个位为真

第 1 步:首先将二进制的 (..0001) 1 移动到左 7 步,使其成为 (..10000000)。
第 2 步:接下来,按位或使用数字。
第 3 步:由于 1 OR 0 = 1 和 1 OR 1 = 1,这会将第 7设置为 1,而不会影响其他位。

将位设置为 false:

例如,在位置 7 将位重置为 false

第 1 步:首先将二进制的 1(即 (..0001))移动到左 7 步,使其成为 (..10000000)。
第 2 步:将位反转为 (…1101111111)。
步骤 3:对数字进行 AND 运算。
第 4 步:由于 1 AND 0 = 0, 0 AND 0 = 0, 1 AND 1 = 1,这会将第 7设置为 1,而不会影响其他位。

获取第i位的值:

例如,要获取第 7的值-

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
// Driver code
int main()
{
  // This is an integer variable
  // used as a container
  int myBoolContainer = 0;
   
  // 7th bit will be used for sample
  int workingBit = 7;
   
  // Setting ith bit
  cout << "Setting " <<
           workingBit << "th bit to 1\n";
   
  myBoolContainer |= (1 << workingBit);
   
  // Printing the ith bit
  cout << "Value at " << workingBit <<
          "th bit = " <<
          ((myBoolContainer >> workingBit) & 1) <<
          "\n\n"; 
   
  // Resetting the ith bit
  cout << "Resetting " << workingBit <<
          "th bit to 0\n";
  myBoolContainer &= ~(1 << 7);
   
  // Printing the ith bit
  cout << "Value at " << workingBit <<
          "th bit = " <<
          ((myBoolContainer >> workingBit) & 1);
}


Java
// Java program to implement
// the above approach
import java.io.*;
 
// Driver code
class GFG
{
    public static void main (String[] args)
    {
          // This will be the integer variable
        // used as boolean container
        int myBoolContainer = 0;
   
        // 7th bit will be used for sample
        int workingBit = 7;
 
        // Setting ith bit
        System.out.println(
        "Setting " + workingBit +
        "th bit to 1");
       
        myBoolContainer |= (1 << workingBit);
 
        // Printing the ith bit
        System.out.println(
        "Value at " + workingBit+"th bit = " +
        ((myBoolContainer >> workingBit) & 1) +
        "\n"); 
 
        // Resetting the ith bit
        System.out.println(
        "Resetting " + workingBit +
        "th bit to 0");
         
        myBoolContainer &= ~(1 << 7);
 
        // Printing the ith bit
        System.out.println(
        "Value at " + workingBit +
        "th bit = " +
        ((myBoolContainer >>workingBit) & 1));
    }
}


Python
# Python program to implement
# the above approach
# This will be the integer variable
# used as boolean container
myBoolContainer = 0;
   
# 7th bit will be used as example
workingBit = 7;
 
# Setting ith bit
print("Setting " + str(workingBit) +
      "th bit to 1");
myBoolContainer |= (1 << workingBit);
 
# Printing the ith bit
print("Value at " + str(workingBit) +
      "th bit = " + str((myBoolContainer >>
                         workingBit) & 1) + "\n"); 
 
# Resetting the ith bit
print("Resetting " + str(workingBit) +
      "th bit to 0");
myBoolContainer &= ~(1 << 7);
 
# Printing the ith bit
print("Value at " + str(workingBit) +
      "th bit = " + str((myBoolContainer >>
                         workingBit) & 1))


C#
//C# code for the above approach
using System;
public class GFG {
 
    static public void Main()
    {
 
        // This will be the integer variable
        // used as boolean container
        int myBoolContainer = 0;
 
        // 7th bit will be used for sample
        int workingBit = 7;
 
        // Setting ith bit
        Console.WriteLine("Setting " + workingBit
                          + "th bit to 1");
 
        myBoolContainer |= (1 << workingBit);
 
        // Printing the ith bit
        Console.WriteLine(
            "Value at " + workingBit + "th bit = "
            + ((myBoolContainer >> workingBit) & 1) + "\n");
 
        // Resetting the ith bit
        Console.WriteLine("Resetting " + workingBit
                          + "th bit to 0");
 
        myBoolContainer &= ~(1 << 7);
 
        // Printing the ith bit
        Console.WriteLine(
            "Value at " + workingBit + "th bit = "
            + ((myBoolContainer >> workingBit) & 1));
    }
}
 
// This code is contributed by Potta Lokesh


Javascript
// Javascript program to implement
// the above approach
// This is an integer variable
// used as a container
var myBoolContainer = 0;
 
// 7th bit will be used sample
var workingBit = 7;
   
// Setting ith bit
console.log("Setting " + workingBit +
            "th bit to 1\n");
myBoolContainer |= (1 << workingBit);
   
//Printing the ith bit
console.log("Value at " + workingBit +
            "th bit = "+ ((myBoolContainer >>
                           workingBit) & 1) + "\n\n");
   
// Resetting the ith bit
console.log("Resetting " + workingBit +
            "th bit to 0\n");
myBoolContainer &= ~(1 << 7);
   
// Printing the ith bit
console.log("Value at " + workingBit +
            "th bit = " + ((myBoolContainer >>
                            workingBit) & 1));


C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
bool checkIsPanagram(string sentence)
{
    // Initializing the container
    int n = 0;
   
    for(char &x:sentence)
    {
        // Checking that the char
        // is Alphabetic
        if(isalpha(x)) 
           
            // setting ith bit to 1
            // if char is 'a' then this will
            // set 0th bit to 1 and so on
            n |= (1 << (tolower(x) - 'a'));           
    }
   
    // decimal number for all ones in last
    // 26 bits in binary is 67108863
    return n == 67108863;
}
 
// Driver code
int main()
{
  string s =
  "Pack mY box witH fIve dozen liquor jugs";
  cout << checkIsPanagram(s);
}


Java
// Java program to implement
// the above approach
import java.io.*;
class Panagram
{
  public boolean checkIsPanagram(
                 String sentence)
  {
      // Initializing the container
      int n = 0;
     
        int size = sentence.length();
        for(int i = 0; i < size; i++)
        {
            // Storing current character
            // in temp variable
            char x = sentence.charAt(i);
           
            // checking that the char is Alphabetic
            if(Character.isAlphabetic(x))
            {
                // setting ith bit to 1
                // if char is 'a' then this will
                // set 0th bit to 1 and so on
                n |= (1 << (Character.toLowerCase(x) - 'a'));    
            }
        }
     
        // Decimal number for all ones in last
        // 26 bits in binary is 67108863
        return (n == 67108863);
  }
};
 
// Driver code
class GFG
{
    public static void main (String[] args)
    {
      String s =
      "Pack mY box witH fIve dozen liquor jugs";
      Panagram panagram = new Panagram();
      System.out.println(
             panagram.checkIsPanagram(s));
    }
}


Python
# Python program to implement
# the above approach
def isPanagram(sentence):
   
    # Initializing the container
    n = 0
     
    for char in sentence:
           
        # Checking that the char
        # is Alphabetic
        if char.isalpha():
           
            # setting ith bit to 1
            # if char is a then this will
            # set 0th bit to 1 and so on
            n |= (1 << (ord(char.lower()) -
                        ord('a')))
             
     
    # Decimal number for all ones in
    # last 26 bits in binary is 67108863
    return n == 67108863
 
sentence =
"Pack mY box witH fIve dozen liquor jugs"
print(isPanagram(sentence))


C#
// C# program to implement
// the above approach
using System;
 
class Panagram
{
  public bool checkIsPanagram(
                 String sentence)
  {
     
      // Initializing the container
      int n = 0;
     
        int size = sentence.Length;
        for(int i = 0; i < size; i++)
        {
           
            // Storing current character
            // in temp variable
            char x = sentence[i];
           
            // checking that the char is Alphabetic
            if(char.IsLetter(x))
            {
               
                // setting ith bit to 1
                // if char is 'a' then this will
                // set 0th bit to 1 and so on
                n |= (1 << (char.ToLower(x) - 'a'));    
            }
        }
     
        // Decimal number for all ones in last
        // 26 bits in binary is 67108863
        return (n == 67108863);
  }
};
 
// Driver code
public class GFG
{
    public static void Main(String[] args)
    {
      String s =
      "Pack mY box witH fIve dozen liquor jugs";
      Panagram panagram = new Panagram();
      Console.WriteLine(
             panagram.checkIsPanagram(s));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
Setting 7th bit to 1
Value at 7th bit = 1

Resetting 7th bit to 0
Value at 7th bit = 0

解决 Pangram 字符串:

让我们使用上述方法解决 pangram字符串的问题。

方法:

众所周知,从 (az) 开始的小写英文字母的计数不超过 26。因此,在这种方法中,可以使用恒定大小的 bool 数组。这将优化代码的空间复杂度。

下面是使用布尔数组的 pangram字符串的实现:

C++

// C++ program to implement
// the above approach
#include 
using namespace std;
 
bool checkIsPanagram(string sentence)
{
    // Initializing the container
    int n = 0;
   
    for(char &x:sentence)
    {
        // Checking that the char
        // is Alphabetic
        if(isalpha(x)) 
           
            // setting ith bit to 1
            // if char is 'a' then this will
            // set 0th bit to 1 and so on
            n |= (1 << (tolower(x) - 'a'));           
    }
   
    // decimal number for all ones in last
    // 26 bits in binary is 67108863
    return n == 67108863;
}
 
// Driver code
int main()
{
  string s =
  "Pack mY box witH fIve dozen liquor jugs";
  cout << checkIsPanagram(s);
}

Java

// Java program to implement
// the above approach
import java.io.*;
class Panagram
{
  public boolean checkIsPanagram(
                 String sentence)
  {
      // Initializing the container
      int n = 0;
     
        int size = sentence.length();
        for(int i = 0; i < size; i++)
        {
            // Storing current character
            // in temp variable
            char x = sentence.charAt(i);
           
            // checking that the char is Alphabetic
            if(Character.isAlphabetic(x))
            {
                // setting ith bit to 1
                // if char is 'a' then this will
                // set 0th bit to 1 and so on
                n |= (1 << (Character.toLowerCase(x) - 'a'));    
            }
        }
     
        // Decimal number for all ones in last
        // 26 bits in binary is 67108863
        return (n == 67108863);
  }
};
 
// Driver code
class GFG
{
    public static void main (String[] args)
    {
      String s =
      "Pack mY box witH fIve dozen liquor jugs";
      Panagram panagram = new Panagram();
      System.out.println(
             panagram.checkIsPanagram(s));
    }
}

Python

# Python program to implement
# the above approach
def isPanagram(sentence):
   
    # Initializing the container
    n = 0
     
    for char in sentence:
           
        # Checking that the char
        # is Alphabetic
        if char.isalpha():
           
            # setting ith bit to 1
            # if char is a then this will
            # set 0th bit to 1 and so on
            n |= (1 << (ord(char.lower()) -
                        ord('a')))
             
     
    # Decimal number for all ones in
    # last 26 bits in binary is 67108863
    return n == 67108863
 
sentence =
"Pack mY box witH fIve dozen liquor jugs"
print(isPanagram(sentence))

C#

// C# program to implement
// the above approach
using System;
 
class Panagram
{
  public bool checkIsPanagram(
                 String sentence)
  {
     
      // Initializing the container
      int n = 0;
     
        int size = sentence.Length;
        for(int i = 0; i < size; i++)
        {
           
            // Storing current character
            // in temp variable
            char x = sentence[i];
           
            // checking that the char is Alphabetic
            if(char.IsLetter(x))
            {
               
                // setting ith bit to 1
                // if char is 'a' then this will
                // set 0th bit to 1 and so on
                n |= (1 << (char.ToLower(x) - 'a'));    
            }
        }
     
        // Decimal number for all ones in last
        // 26 bits in binary is 67108863
        return (n == 67108863);
  }
};
 
// Driver code
public class GFG
{
    public static void Main(String[] args)
    {
      String s =
      "Pack mY box witH fIve dozen liquor jugs";
      Panagram panagram = new Panagram();
      Console.WriteLine(
             panagram.checkIsPanagram(s));
    }
}
 
// This code is contributed by 29AjayKumar

Javascript



输出
1