Dado un número entero N , encuentre el complemento a uno del número entero.
Ejemplos:
C++
// CPP program to find 1's complement of N. #include <bits/stdc++.h> using namespace std; // Find the 1's complement of N int findComplement(int num) { int ans = 0; for (int i = 0; num > 0; i++) { ans += pow(2, i) * (!(num % 2)); num /= 2; } return ans; } // Driver code int main() { unsigned int N = 5; cout << findComplement(N); return 0; }
Java
// Java code for the above approach import java.util.*; public class GFG { // Find the 1's complement of N static int findComplement(int num) { int ans = 0; for (int i = 0; num > 0; i++) { if(num % 2 == 0) { ans += (int)Math.pow(2, i) ; } num /= 2; } return ans; } // Driver code public static void main(String args[]) { Integer N = 5; System.out.println(findComplement((int)N)); } } // This code is contributed by Samim Hossain Mondal
Python3
# python3 program to find 1's complement of N. # Find the 1's complement of N def findComplement(num): ans = 0 i = 0 while(True): if num == 0: break ans += pow(2, i) * (not (num % 2)) num //= 2 i += 1 return ans # Driver code if __name__ == "__main__": N = 5 print(findComplement(N)) # This code is contributed by rakeshsahni
C#
// C# code for the above approach using System; class GFG { // Find the 1's complement of N static int findComplement(int num) { int ans = 0; for (int i = 0; num > 0; i++) { if(num % 2 == 0) { ans += (int)Math.Pow(2, i) ; } num /= 2; } return ans; } // Driver code public static void Main() { uint N = 5; Console.Write(findComplement((int)N)); } } // This code is contributed by Samim Hossain Mondal
Javascript
<script> // JavaScript code for the above approach // Find the 1's complement of N function findComplement(num) { let ans = 0; for (let i = 0; num > 0; i++) { ans += Math.pow(2, i) * (!(num % 2)); num = Math.floor(num / 2); } return ans; } // Driver code let N = 5; document.write(findComplement(N)); // This code is contributed by Potta Lokesh </script>