将字符串数字中为偶数位的数字进行翻转,将翻转后的结果进行输出。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param number string字符串
* @return string字符串
*/
public String change (String number) {
// write code here
char[] s = number.toCharArray();
int head = 0;
int tail = s.length-1;
while(head<=tail){
if (Integer.valueOf(s[head])%2!=0){
head++;
}else if (Integer.valueOf(s[tail])%2!=0){
tail--;
}else{
char temp=s[tail];
s[tail] = s[head];
s[head] = temp;
head++;
tail--;
}
}
return new String(s);
}
} import java.util.*;
public class Solution {
/**
*
* @param number string字符串
* @return string字符串
*/
public String change (String number) {
// write code here
int n = number.length();
int i = 0;
int j = n - 1;
char[] a = number.toCharArray();
while (i < j) {
while (i < j && a[i] % 2 != 0) {//Ascll码编号与对应数字的奇偶一致
i++;
}
while (i < j && a[j] % 2 != 0) {
j--;
}
char temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
return new String(a);
}
} import java.util.*;
/*
思路:设置双指针,依次从前后进行判断,遇到偶数交换
可能有的情况如下:
左边为奇数,右边为奇数,指针后移,指针前移
左边为奇数,右边为偶数,左指针后移,右指针等待
左边为偶数,右边为奇数,左指针等待,右指针前移
左边,右边都是偶数,数值交换,左右指针都移动
*/
public class Solution {
/**
*
* @param number string字符串
* @return string字符串
*/
public String change (String number) {
// write code here
if(number.length()<=1)return number;
char[] ch = number.toCharArray();
int left = 0;
int right = ch.length-1;
while(left < right){
int a = ch[left] - '0';
int b = ch[right] - '0';
if(a%2!=0 && b%2 !=0){left++;right--;}
else if(a%2!=0 && b%2==0)left++;
else if(a%2==0 && b%2!=0)right--;
else if(a%2==0 && b%2==0){
char temp = ch[left];
ch[left] = ch[right];
ch[right] = temp;
left++;
right--;
}
}
return String.valueOf(ch);
}
} //字符串转char数组
char[] numbers = number.toCharArray();
//定义左右指针
int left=0;
int right=number.length()-1;
//都找到偶数则交换
while (left<right){
//从左边找到第一个偶数
while(left<right&&numbers[left]%2!=0)
left++;
//从右边找到第一个偶数
while(left<right&&numbers[right]%2!=0)
right--;
//交换
char temp=numbers[left];
numbers[left]=numbers[right];
numbers[right]=temp;
//更新指针
left++;
right--;
}
return String.valueOf(numbers);