fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. int main() {
  6. int t;
  7. cin >> t; // Read the number of test cases
  8. while (t--) {
  9. int n;
  10. cin >> n; // Read the length of the string
  11. string s;
  12. cin >> s; // Read the binary string
  13.  
  14. int count_0 = 0, count_1 = 0;
  15. int transitions = 0;
  16.  
  17. // Count the number of '0's and '1's and count transitions
  18. for (int i = 0; i < n; i++) {
  19. if (s[i] == '0') {
  20. count_0++;
  21. // Check for transition from '1' to '0'
  22. if (i > 0 && s[i - 1] == '1') {
  23. transitions++;
  24. }
  25. } else {
  26. count_1++;
  27. // Check for transition from '0' to '1'
  28. if (i > 0 && s[i - 1] == '0') {
  29. transitions++;
  30. }
  31. }
  32. }
  33.  
  34. // If there are no '0's or no '1's, no moves are needed
  35. if (count_0 == 0 || count_1 == 0) {
  36. cout << 0 << endl;
  37. } else {
  38. // The number of moves is the number of transitions + 1
  39. cout << transitions + 1 << endl;
  40. }
  41. }
  42. return 0;
  43. }
Success #stdin #stdout 0s 5284KB
stdin
5
5
00110
4
1111
3
001
5
00000
3
101
stdout
3
0
2
0
3