解法一:字符串处理

朴实无华的字符串处理问题,注意考虑和为0的情况。

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. public class Main {
  5. public static void main(String[] args) throws IOException {
  6. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  7. String[] input = reader.readLine().split(" ");
  8. int a = Integer.parseInt(input[0]);
  9. int b = Integer.parseInt(input[1]);
  10. int c = a + b;
  11. if (c == 0) {
  12. System.out.println(0);
  13. return;
  14. }
  15. int temp = Math.abs(c);
  16. int index = 0;
  17. StringBuilder sBuilder = new StringBuilder();
  18. while (temp != 0) {
  19. if ((index > 0) && (index % 3 == 0)) {
  20. sBuilder.append(',');
  21. }
  22. ++index;
  23. sBuilder.append(temp % 10);
  24. temp /= 10;
  25. }
  26. if (c < 0) {
  27. sBuilder.append('-');
  28. }
  29. System.out.println(sBuilder.reverse().toString());
  30. }
  31. }