![]() |
VOOZH | about |
The std::abs(), std::labs() and std::llabs() in C++ are built-in functions that are used to find the absolute value of any number that is given as the argument. Absolute value is the value of a number without any sign. These functions are defined inside the <cmath> header file.
In this article, we will learn how to use std::abs(), std::labs() and std::llabs() in C++.
Table of Content
The std::abs() in C++ is used to find the absolute value of given number. The value returned by std::abs() function is of type int.
std::abs(num)
Parameters
Return Value
abs(22) = 22 abs(-43) = 43
Time Complexity: O(1)
Auxiliary Space: O(1)
In C++, integer type ranges from INT_MIN = 2147483647 (considering 32-bit compiler) to INT_MAX = 2147483647. As we can see, converting the INT_MIN to its absolute value will result in a value larger than the max value of the int type. So, it will be returned to its 2's complement. This happens with every integer type whether it's a long int or a long long int. So, it is recommended to check for this case when determining the absolute values for ints.
The std::labs() in C++ is also used to find the absolute value of given number similar to abs() function but it returns the absolute value as long int as compared to int for abs() function.
std::labs(num)
Parameters
Return Value
labs(227787989) = 27787989 labs(-438989898) = 438989898
Time Complexity: O(1)
Auxiliary Space: O(1)
The std::llabs() in C++ does the same as abs() and labs() function. It returns the absolute value of given number but in the form of long long integer.
llabs(num)
Parameters
Return Value
llabs(22778798908) = 22778798908 llabs(-43898989878) = 43898989878
Time Complexity: O(1)
Auxiliary Space: O(1)