1095. 最大的交换
给定一个非负整数, 你可以选择交换它的两个数位. 返回你能获得的最大的合法的数.
样例
样例1:
输入: 2736
输出: 7236
解释: 交换数字2和数字7.
样例2:
输入: 9973
输出: 9973
解释: 不用交换.
代码区:
public class Solution {
/**
* username:softstarhhy
* @param num: a non-negative intege
* @return: the maximum valued number
*/
public int maximumSwap(int num) {
// Write your code here
int[] maxnum=new int[8];
char[] maxnumchars=new char[8];
String numstr=""+num;
int loc=0;
int maxnumflag=0;
maxnumchars=numstr.toCharArray();
char mid='\0';
int times=0;//每次遍历的跳出条件 既是是否需要再次遍历该循环
int j=0;
boolean flag=false;//遍历该循环附加条件 如果位置没有变化并且值都不相等才会进行再次遍历
for(int i=0;i<maxnumchars.length;i++)
{
maxnumflag=maxnumchars[i] - '0';
if(times==i&&flag==true)
{
break;
}
for( j=i;j<maxnumchars.length;j++)
{
if((maxnumchars[j] - '0')>=maxnumflag)
{
if(loc==(i)&&j==(maxnumchars.length-1))
{ flag=false;
times++;
break;
}
loc=j;
maxnumflag=maxnumchars[j]-'0';
if(j==maxnumchars.length-1)
{
mid= maxnumchars[i];
maxnumchars[i]=maxnumchars[loc];
maxnumchars[loc]=mid;
times++;
flag=true;
if(loc!=i&&maxnumchars[loc]==maxnumchars[i])
{
flag=false;
}
}
}else if((maxnumchars[j] - '0')<maxnumflag)
{
if(loc==(i)&&j==(maxnumchars.length-1))
{
flag=false;
times++;
break;
}
loc=loc;
maxnumflag=maxnumflag;
if(j==maxnumchars.length-1)
{
mid= maxnumchars[i];
maxnumchars[i]=maxnumchars[loc];
maxnumchars[loc]=mid;
times++;
flag=true;
if(loc!=i&&maxnumchars[loc]==maxnumchars[i])
{
flag=false;
}
}
}
}
}
String s=String.valueOf(maxnumchars);
int numresult=Integer.parseInt(s);
return numresult;
}
}