整数加一.c 707 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <stdio.h>
  2. #include <string.h>
  3. #define MAX_LENGTH 52
  4. void addone(char num[]);
  5. int main() {
  6. char num[MAX_LENGTH];
  7. scanf("%s", num);
  8. addone(num);
  9. printf("%s\n", num);
  10. return 0;
  11. }
  12. void addone(char num[]) {
  13. int length = strlen(num);
  14. int carry = 1;
  15. int i;
  16. for (i = length - 1; i >= 0; i--) {
  17. int digit = num[i] - '0' + carry;
  18. num[i] = (digit % 10) + '0';
  19. carry = digit / 10;
  20. }
  21. if (carry > 0) {
  22. if (length == MAX_LENGTH - 1) {
  23. printf("\n");
  24. return;
  25. }
  26. int i;
  27. for (i = length; i >= 0; i--) {
  28. num[i + 1] = num[i];
  29. }
  30. num[0] = carry + '0';
  31. }
  32. }