VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-find-absolute-value-of-a-given-number/

⇱ Program to find absolute value of a given number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find absolute value of a given number

Last Updated : 15 Jul, 2025

Given an integer N, The task is to find the absolute value of the given integer.

Examples: 

Input: N = -6 
Output: 6
Explanation: The absolute value of -6 is 6 which is non negative

Input: N = 12 
Output: 12 

Naive Approach: To solve the problem follow the below idea:

The absolute value of any number is always positive. For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number

Learn More, Positive and Negative Numbers

Below is the implementation of the above approach.


Output
 12

Time Complexity: O(1)
Auxiliary Space: O(1)

To solve the problem follow the below idea:

Negative numbers are stored in the form of 2s complement, to get the absolute value we have to toggle bits of the number and add 1 to the result. 

Follow the steps below to implement the idea: 

  • Set the mask as right shift of the integer by 31 (assuming integers are stored using 32 bits) mask = n >> 31
  • For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number i.e. mask + n   
  • XOR of mask + n and mask gives the absolute value i.e.   

Below is the implementation of the above approach.


Output
12

Time Complexity: O(1)
Auxiliary Space: O(1)

Find the absolute value of a given number Using the inbuilt abs() function:

To solve the problem follow the below idea:

The inbuilt function abs() in stdlib.h library finds the absolute value of any number. This can be used to find absolute value of any integer.

Below is the implementation of the above approach: 


Output
12

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: