Avatar ·

How to check if a number is a power of two in C#?

Hello everyone! I'm a beginner in C# and came across a task: I need to write a method that checks whether an integer is a power of two (1, 2, 4, 8, 16, 32, etc.). It seems like a simple task, but I can't come up with an elegant solution.\n\nSo far I've written this code:\n\n```csharp\npublic static bool IsPowerOfTwo(int n)\n{\n if (n <= 0) return false;\n while (n > 1)\n {\n if (n % 2 != 0) return false;\n n = n / 2;\n }\n return true;\n}\n```\n\nIt seems to work, but I think it's too cumbersome and inefficient. I've heard there's some clever way with bitwise operations, but I don't understand how it works. Can you suggest a more correct and faster solution?\n\nI'm especially interested in:\n1. How to do the check without loops?\n2. What are bitwise operations and how