#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
std::stoull(str)
for unsigned long long instead. Thestrtol
(andstd::stol
in C++) is for signed longs. – Zirconiachar
instead ofunsigned char
asstd::string
useschar
. – Hyperbolic