Simple and Easy Solution with Intuition | ✅Beats 100% | Java | Python 🔥🔥
🔹 Approach 1: Brute Force (O(logN))IntuitionIterate from num and increment until we find a number where all bits are set.Algorithm
Start with num.
Increment num
## **🔹 Approach 1: Brute Force (O(logN))**  

### **Intuition**  
Iterate from `num` and increment until we find a number where **all bits are set**.  

### **Algorithm**  
1. Start with `num`.  
2. Increment `num` until `num & (num + 1) == 0`.  
3. Return the result.  

### **Implementation**
#### **Java**
```java
class Solution {
    public int nearestAllSetBits(int num) {
        while ((num & (num + 1)) != 0) {
            num++;
        }
        return num;
    }
}
```
#### **Python**
```python
class Solution:
    def nearestAllSetBits(self, num: int) -> int:
        while (num & (num + 1)) != 0:
            num += 1
        return num
```
### **Complexity Analysis**
- **Time Complexity:** `O(logN)` – Iterates until reaching a power of `2 - 1`.  
- **Space Complexity:** `O(1)` – Uses a single variable.  

---

## **🔹 Approach 2: Optimized Bitwise (O(1))**  

### **Intuition**  
Instead of iterating, leverage bitwise operations:  

###### Use this formula:- 
##### **Nearest all-1s number = (Next power of 2) - 1**

This works because `2^x - 1` always has all bits set.  

### **Algorithm**  
1. Find the **next power of 2** of `num`.  
2. Subtract `1` to get all bits set.  

### **Implementation**
#### **Java**
```java
class Solution {
    public int nearestAllSetBits(int num) {
        int nextPowerOfTwo = Integer.highestOneBit(num) << 1;
        return nextPowerOfTwo - 1;
    }
}
```
#### **Python**
```python
class Solution:
    def nearestAllSetBits(self, num: int) -> int:
        nextPowerOfTwo = 1 << num.bit_length()
        return nextPowerOfTwo - 1
```

### **Complexity Analysis**
- **Time Complexity:** `O(1)` – Uses only bitwise operations.  
- **Space Complexity:** `O(1)` – No extra memory usage.  

---

## **🔍 Comparison Table**  

| Approach | Time Complexity | Space Complexity | Key Idea |
|----------|----------------|----------------|----------|
| **Brute Force** | `O(logN)` | `O(1)` | Increment `num` until all bits are `1`. |
| **Bitwise (Optimal)** | `O(1)` | `O(1)` | Use bitwise shifts to compute the result instantly. |

---

## **Conclusion**  
- **Brute Force** is simple but inefficient for large numbers.  
- **Bitwise Optimization** provides an elegant `O(1)` solution using `Integer.highestOneBit()` or `bit_length()`.  

For efficient solutions, **bitwise operations** are the preferred approach. 🚀

---
### ✅ **If you found this explanation helpful, don't forget to upvote!** 🚀  
![image.png](https://assets.leetcode.com/users/images/cc1fbde5-1c73-4314-8b31-013087a7d852_1741462236.1272159.png)

['Bit Manipulation', 'Bitmask', 'Java', 'Python3']