我有一个像4590897这样的整数值,我要做的是,我必须以某种方式对这个整数进行混洗,这样我才能获得输出4759980,就像传送第一个数字和最后一个数字并创建一个新数字一样。整数值可以是任意值。
我尝试了一些代码,例如通过转换char数组中的数字,然后对其进行迭代并将其附加到StringBuilder中,但是没有得到期望的结果。 下面的代码
public final class class2 {
public static void main(String[] args) {
int a = 15670;
StringBuilder s2 = new StringBuilder();
String s1 = String.valueOf(a);
char[] ch = s1.toCharArray();
//System.out.println(ch.length);
Outerloop:
for(int i = 0; i <=ch.length-1;i++){
//System.out.println(ch[i]);
for(int j = ch.length-1; j >=0; j--){
s2.append(ch[i]);
s2.append(ch[j]);
break;
}
}
System.out.println(s2);
}
}
我必须以某种方式对这个整数进行混洗,以便获得4759980的输出
答案 0 :(得分:0)
那呢。首先,您将数字分解为数字,然后通过选择一个随机位置来将数字随机地添加回去……
public int scramble(int number) {
//Convert the integer to an Array of strings where each string represents a digit
String[] digits = Integer.toString(number).split("");
//Add the individual digits to a list in random order, using a random position
List<String> resultList = new ArrayList<>();
for (String digit: digits) {
int position = (int) (Math.random()*(resultList.size()));
resultList.add(position, digit);
}
//Convert the list with digits in random order to a string
String resultString ="";
for (String digit: resultList) {
resultString += digit;
}
//Convert the resulting string to an integer and return
return Integer.parseInt(resultString);
}
答案 1 :(得分:0)
试试看!我首先将数字转换为字符串。然后,我添加第一个和最后一个数字,第二个和之前的最后一个数字,依此类推。然后,我确保字符串的长度与开始的长度相同(对于数字为奇数的数字)。>
public int scramble(int number) {
String numberString = Integer.toString(number);
int numberLength = numberString.length();
String result = "";
for (int i = 0; i < (numberLength + 2) / 2; i++) {
result += numberString.charAt(i);
result += numberString.charAt(numberLength - i - 1);
}
//Making sure that the resulting string is the same length as the original
//Initially, the result for a number with an odd number of digits, such as 12345
//will be 152344. So you need to make sure the last digit is removed.
result = result.substring(0, numberLength);
return Integer.parseInt(result);
}
答案 2 :(得分:0)
采用两个指针,开始和结束。遍历字符串,并将字符从头到尾附加到新字符串。递增开始和递减结束,直到开始和结束相同。
"DataRows created"