java code for input: 5607890123 output: 3201980765 here 0 position should not be changed
tried but not succeeded
String str = "5607890123";
int len = str.length();
for(int i = len -1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
CodePudding user response:
Here is just a fast approach to the problem, which does what you require. There is no chance that your code snippet does it, since you just reverse the string, without any other control
String str = "5607890123";
String rev = "";
for (int i = str.length()-1; i >= 0; i--) {
int compl = str.length() - i - 1;
if (str.charAt(compl) == '0') {
rev = "0";
rev = str.charAt(i);
} else {
if (str.charAt(i) == '0') {
} else {
rev = str.charAt(i);
}
}
}
System.out.println(rev);
CodePudding user response:
Another option using "pointers" coming from left and right, skipping if one character at pointer is "0":
var input = "5607890123";
var chars = input.toCharArray();
var left = 0;
var right = chars.length - 1;
while (left < right) {
var charLeft = chars[left];
var charRight = chars[right];
if (charLeft == '0') {
left ;
continue;
}
if (charRight == '0') {
right--;
continue;
}
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left ;
right--;
}
var result = new String(input);