Hihi is the grandfather of all geeks in IIITA. He and his crazy ideas.....Huh..... Currently, hihi is working on his most famous project named 21 Lane, but he is stuck at a tricky segment of his code.
Hihi wants to assign some random IP addresses to users, but he won't use rand(). He wants to change the current IP of the user's computer to the IP such that its hash is the next hash greater than the hash of the original IP and differs by only 1 bit from the hash of the original IP.
Smart Hihi already hashed the IP to some integer using his personal hash function. What he wants from you is to convert the given hashed IP to the required IP X as mentioned above.
OK, just find the smallest number greater than n with exactly 1 bit different from n in binary form
Example:
Input: n = 6
Output: 7
Approach
Java
public class CrazyBits {public static void main(String[] args) {long n = 6;String b = binary(n);long res = n + 1;for (long i = n + 1;; i++) {String a = binary(i);boolean f = check(a, b);if (f == true) {res = i;break;}}System.out.println(res);}static String binary(long a) {String res = "";while (a > 0) {if (a % 2 == 1)res += '1';elseres += '0';a = a / 2;}return res;}static boolean check(String a, String b) {int n = a.length(), m = b.length();if (n != m)return true;else {int cnt = 0;for (int i = 0; i < n; i++)if (a.charAt(i) != b.charAt(i))cnt++;if (cnt == 1)return true;return false;}}}
C++
#include <bits/stdc++.h>using namespace std;string binary(long long a){string res = "";while (a){if (a & 1)res += '1';elseres += '0';a = a / 2;}return res;}bool check(string a, string b){int n = a.size(), m = b.size();if (n != m)return true;else{int cnt = 0;for (int i = 0; i < n; i++)if (a[i] != b[i])cnt++;if (cnt == 1)return true;return false;}}int main(){long long n = 6;string b = binary(n);long long res = n + 1;for (long long i = n + 1;; i++){string a = binary(i);bool f = check(a, b);if (f == 1){res = i;break;}}cout << res << "\n";}
No comments:
Post a Comment