fork download
  1. #include <string>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <algorithm>
  5.  
  6. std::string i32_u10( int32_t n )
  7. {
  8. auto str = std::to_string( 0x7FFFFFFF & (n >> 1) );
  9. char cy = n & 1;
  10. for( int i = str.size()-1; i >= 0; -- i ){
  11. int n = ((str[i] - '0') << 1) + cy;
  12. str[i] = '0' + (n % 10);
  13. cy = (n >= 10)? 1 : 0;
  14. }
  15. return ( cy != 0 )? "1" + str : str;
  16. }
  17.  
  18. void test( int32_t n, std::string ans )
  19. {
  20. auto str = i32_u10( n );
  21. printf( " %11ds %11uu 0x%08X => %10s %s\n", n, n, n, str.c_str(), (str == ans)? "OK" : "NG" );
  22. }
  23.  
  24. int main(void)
  25. {
  26. test( 0, "0" );
  27. test( 1, "1" );
  28. test( 1234567, "1234567" );
  29. test( 0x7FFFFFFF, "2147483647" );
  30. test( 0x80000000, "2147483648" );
  31. test( 0x80000001, "2147483649" );
  32. test( 0xFFFFFFFF, "4294967295" );
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 4932KB
stdin
Standard input is empty
stdout
           0s           0u  0x00000000  =>           0  OK
           1s           1u  0x00000001  =>           1  OK
     1234567s     1234567u  0x0012D687  =>     1234567  OK
  2147483647s  2147483647u  0x7FFFFFFF  =>  2147483647  OK
 -2147483648s  2147483648u  0x80000000  =>  2147483648  OK
 -2147483647s  2147483649u  0x80000001  =>  2147483649  OK
          -1s  4294967295u  0xFFFFFFFF  =>  4294967295  OK