我试图从数字中选择偶数,并通过向它添加1将它们转换为奇数
示例输入/输出
n = 258463,ans = 359573
int n=26540;
System.out.println("n= "+n+", ans= "+even2odd(n));
n=9528;
System.out.println("n= "+n+", ans= "+even2odd(n));
public static int even2odd(int n)
{
while ( n > 0 ) {
if (n%2==0) {
n +=1;
}
System.out.print( n % 10);
n = n / 10;
}
int ans = n;
return ans;
}
正如你所见,我设法将所有偶数转换为奇数,但我不知道如何将它们反转为顺序并将其输出到正确的位置
答案 0 :(得分:3)
Aaaaaannnd一个班轮来到这里
int i = Integer.parseInt(Integer.toString(26540).replaceAll("2", "3").replaceAll("4", "5").replaceAll("6", "7").replaceAll("8", "9"));
答案 1 :(得分:2)
你可以这样做:
public static int even2odd(int n)
{
StringBuilder result = new StringBuilder();
while(n > 0)
{
int firstDigit = n %10;
if(firstDigit%2==0)
++firstDigit;
result.append(firstDigit);
n = n/10;
}
return Integer.parseInt(result.reverse().toString());
}
答案 2 :(得分:0)
怎么样:
String numString = n+"";
String outString = "";
for(int i=0; i<numString.length;i++){
int digit = Character.getNumericValue(numString.charAt(i));
if(digit%2==0) digit++;
outString+=digit;
}
int out = Integer.parseInt(outString);
答案 3 :(得分:0)
如果要求您不使用String或Integer。
public static int even2odd(int n) {
int ans = 0;
int place = 1;
while ( n > 0 ) {
if (n%2==0) {
n +=1;
}
ans = ans+((n%10)*place);
place = place*10;
n = n / 10;
}
System.out.print( ans);
return ans;
}