Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void printWithComma(long long a) {
  5. const int max_digit_in_long_long = 26; // long long のカンマと符合を含んだ最大文字数は26桁 -9,223,372,036,854,775,808
  6. char buffer[max_digit_in_long_long + 1]; // null 文字を含めた最大桁数をアロケート
  7.  
  8. buffer[max_digit_in_long_long] = 0; // 最後をnull 文字で埋めておく。
  9. char* p = &buffer[max_digit_in_long_long - 1];
  10.  
  11. long long temp = abs(a);
  12. if (temp < 0) { // -9,223,372,036,854,775,808 に対する正の値はないので、特殊ケースとして処理
  13. printf("-9,223,372,036,854,775,808\n");
  14. return;
  15. }
  16.  
  17. *p-- = '0' + temp % 10;
  18. temp = temp / 10;
  19.  
  20. int digit = 0;
  21.  
  22. while (temp != 0) {
  23. digit++;
  24. if (digit % 3 == 0) {
  25. *p-- = ',';
  26. }
  27. *p-- = '0' + temp % 10;
  28. temp = temp / 10;
  29. }
  30.  
  31. if (a > 0) {
  32. *p = '+';
  33. } else if (a < 0) {
  34. *p = '-';
  35. } else {
  36. *p = ' ';
  37. }
  38.  
  39. printf("%s\n", p);
  40. }
  41.  
  42. int main()
  43. {
  44. printWithComma(999);
  45. printWithComma(18999);
  46. printWithComma(LLONG_MIN + 1);
  47. printWithComma(0);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement