Dado un entero N , la tarea es encontrar el valor absoluto del entero dado.
Ejemplos:
Entrada: N = -6
Salida: 6
Entrada: N = 12
Salida: 12
Método 1: enfoque ingenuo: dado que el valor absoluto de cualquier número siempre es positivo. Para cualquier número positivo, el valor absoluto es el número mismo y para cualquier número negativo, el valor absoluto es (-1) multiplicado por el número negativo.
C++
// C++ program for Method 1 #include <bits/stdc++.h> using namespace std; // Function to find the absolute value void findAbsolute(int N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value cout << " " << N; } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; } // This code is contributed by shivanisinghss2110
C
// C program for Method 1 #include <stdio.h> // Function to find the absolute value void findAbsolute(int N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value printf("%d ", N); } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; }
Java
// Java program for Method 1 class GFG{ // Function to find the absolute value static void findAbsolute(int N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value System.out.printf("%d ", N); } // Driver Code public static void main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program for Method 1 # Function to find the absolute value def findAbsolute(N): # If the number is less than # zero, then multiply by (-1) if (N < 0): N = (-1) * N; # Print the absolute value print(N); # Driver code if __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This is code contributed by amal kumar choubey
C#
// C# program for Method 1 using System; using System.Collections.Generic; class GFG{ // Function to find the absolute value static void findAbsolute(int N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value Console.Write("{0} ", N); } // Driver Code public static void Main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by sapnasingh4991
Javascript
<script> // Javascript program for Method 1 // Function to find the absolute value function findAbsolute(N) { // If the number is less than // zero, then multiply by (-1) if (N < 0) { N = (-1) * N; } // Print the absolute value document.write(" " + N); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by suresh07. </script>
12
Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)
Método 2: uso de máscara de bits: dado que los números negativos se almacenan en forma de complemento a 2 , para obtener el valor absoluto, tenemos que alternar bits del número y agregar 1 al resultado. A continuación se muestran los pasos:
- Establezca la máscara como desplazamiento a la derecha de un entero por 31 (suponiendo que los enteros se almacenen usando 32 bits).
mask = n >> 31
2. Para números negativos, el paso anterior establece la máscara como 1 1 1 1 1 1 1 1 y 0 0 0 0 0 0 0 0 para números positivos. Agregue la máscara al número dado.
mask + n
3. XOR de mask +n y mask da el valor absoluto.
(mask + n)^mask
C++
// C++ program for Method 2 #include <bits/stdc++.h> using namespace std; #define CHAR_BIT 8 // Function to find the absolute // value void findAbsolute(int N) { // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask cout << ((mask + N) ^ mask); } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; } // This code is contributed by Code_Mech
C
// C program for Method 2 #include <stdio.h> #define CHAR_BIT 8 // Function to find the absolute // value void findAbsolute(int N) { // Find mask int mask = N >> (sizeof(int) * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask printf("%d ", (mask + N) ^ mask); } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; }
Java
// Java program for Method 2 class GFG{ static final int CHAR_BIT = 8; // Function to find the absolute value static void findAbsolute(int N) { // Find mask int mask = N >> (Integer.SIZE / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask System.out.printf("%d ", (mask + N) ^ mask); } // Driver Code public static void main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program for Method 2 import sys CHAR_BIT = 8; # Function to find the absolute value def findAbsolute(N): # Find mask mask = N >> (sys.getsizeof(int()) // 8 * CHAR_BIT - 1); # Print the absolute value # by (mask + N)^mask print((mask + N) ^ mask); # Driver Code if __name__ == '__main__': # Given integer N = -12; # Function call findAbsolute(N); # This code is contributed by 29AjayKumar
C#
// C# program for Method 2 using System; class GFG{ static readonly int CHAR_BIT = 8; // Function to find the absolute value static void findAbsolute(int N) { // Find mask int mask = N >> (sizeof(int) / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask Console.Write((mask + N) ^ mask); } // Driver Code public static void Main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript program for Method 2 let CHAR_BIT = 8; // Function to find the absolute value function findAbsolute(N) { // Find mask let mask = N >> (4 / 8 * CHAR_BIT - 1); // Print the absolute value // by (mask + N)^mask document.write((mask + N) ^ mask); } // Given integer let N = -12; // Function call findAbsolute(N); // This code is contributed by mukesh07. </script>
12
Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)
Método 3: uso de la función abs() incorporada: la función abs() incorporada en la biblioteca stdlib.h encuentra el valor absoluto de cualquier número.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for Method 3 # include<bits/stdc++.h> using namespace std; // Function to find the absolute // value void findAbsolute(int N) { // Find absolute int X = abs(N); // Print the absolute value cout << X; } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; } // This code is contributed by Nidhi_biet
C
// C program for Method 3 #include <stdio.h> #include <stdlib.h> // Function to find the absolute // value void findAbsolute(int N) { // Find absolute int X = abs(N); // Print the absolute value printf("%d ", X); } // Driver Code int main() { // Given integer int N = -12; // Function call findAbsolute(N); return 0; }
Java
// Java program for Method 3 class GFG{ // Function to find the absolute // value static void findAbsolute(int N) { // Find absolute int X = Math.abs(N); // Print the absolute value System.out.printf("%d", X); } // Driver Code public static void main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by sapnasingh4991
Python3
# Python3 program for Method 3 import math # Function to find the absolute # value def findAbsolute(N): # Find absolute X = abs(N); # Print the absolute value print(X); # Driver Code # Given integer N = -12; # Function call findAbsolute(N); # This code is contributed by Nidhi_biet
C#
// C# program for Method 3 using System; class GFG{ // Function to find the absolute // value static void findAbsolute(int N) { // Find absolute int X = Math.Abs(N); // Print the absolute value Console.Write("{0}", X); } // Driver Code public static void Main(String[] args) { // Given integer int N = -12; // Function call findAbsolute(N); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript program for Method 3 // Function to find the absolute // value function findAbsolute(N) { // Find absolute let X = Math.abs(N); // Print the absolute value document.write(X); } // Given integer let N = -12; // Function call findAbsolute(N); </script>
12
Tiempo Complejidad: O(1)
Espacio Auxiliar: O(1)