#include <cinttypes>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
uint64_t descendingOrder(uint64_t a)
{
string str = to_string(a);
sort(str.begin(),str.end(),[](unsigned char a , unsigned char b) { return a>b;});
cout<<"sorted string:" <<str<<endl;
cout<<"value :"<<strtol(str.c_str(),nullptr,10)<<endl;
return strtol(str.c_str(),nullptr,10);
}
int main()
{
descendingOrder(9223372036854775807L);
}
sorted string:9887777655433322200
value :9223372036854775807
Why are the sorted string: and value: are different? It seems like value: took the original string somehow even after sorting. Where is the mistake? Is it UB?
Code: Online code
9887777655433322200 is out of range for a
longon your architecture.That's why
errnogets set toERANGEandLONG_MAX(which happens to be your input) is returned. Note that an implementation may also useLLONG_MINorLLONG_MINor evenLONG_MIN. You need to checkerrnoin order to know whether the conversion withstrtolworked.If you used
std::stolyou would have ended up with anstd::out_of_rangeexception instead. Whether you want to use exceptions is up to you, but meanwhile, use eitherstd::strtoullforunsigned long long(and checkerrno) or usestd::stoull(and keep possible exceptions in mind).See
[string.conversions]in the C++ standard or the links above to cppreference.com for more information.