![]() |
VOOZH | about |
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 negativeInput: 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.
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:
Below is the implementation of the above approach.
12
Time Complexity: O(1)
Auxiliary Space: O(1)
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:
12
Time Complexity: O(1)
Auxiliary Space: O(1)