fork download
  1. public class Main {
  2.  
  3. public static void main(String[] args) {
  4. String S = "10101010";
  5.  
  6. StringBuilder result = new StringBuilder();
  7. int count = 0;
  8.  
  9. int i = 0;
  10. while (i < S.length() - 1) {
  11. // Check for "01"
  12. if (S.charAt(i) == '0' && S.charAt(i + 1) == '1') {
  13. result.append("10");
  14. count++;
  15. i += 2; // skip next character
  16. } else {
  17. result.append(S.charAt(i));
  18. i++;
  19. }
  20. }
  21.  
  22. // Append last character if not processed
  23. if (i < S.length()) {
  24. result.append(S.charAt(i));
  25. }
  26.  
  27. System.out.println("Modified String: " + result);
  28. System.out.println("Replacement Count: " + count);
  29. }
  30. }
Success #stdin #stdout 0.14s 55472KB
stdin
Standard input is empty
stdout
Modified String: 11010100
Replacement Count: 3