I'm trying to figure out how to take in an integer and rearrange them so that every alternating character is saved (So the [1, 2, 3, 4, 5, 6] would return [1, 4, 2, 5, 3, 6]). I think a queue would be the best to use for this problem so here's what I have so far. It returns [3, 1, 4, 5, 2, 6], but I'm not sure how I can get it to return the alternating form above :
import java.util.*;
public class everyOtherInteger {
public static void main(String[] args) {
Queue <Integer> sort = new LinkedList<Integer>();
String s = "123456";
for (int i = 0; i < s.length(); i ) {
sort.add(Integer.parseInt(s.charAt(i) ""));
if (i%2 == 0) {
int a = sort.remove();
sort.add(a);
}
else {
}
}
System.out.println(sort);
}
}
CodePudding user response:
Just build the list differently. No queue required.
You can add half the numbers at the start, the add the rest in-between each.
List<Integer> nums = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int limit = sc.nextInt(); // 6
int value = 1;
for (int i = 0; i < limit / 2; i ) {
nums.add(value );
}
for (int i = 1; i < limit; i =2) {
nums.add(i, value );
}
System.out.println(nums); // [1, 4, 2, 5, 3, 6]
CodePudding user response:
I would just add them one after the other in a single loop. The second element is simply the current one plus the offset where the offset is half the array length.
- read in the number as a string.
- and work with the character array of digits.
Scanner input = new Scanner(System.in);
String val = input.next();
List<Integer> result =new ArrayList<>();
char[] digits = val.toCharArray();
int half = digits.length/2;
for(int i = 0; i < half; i ) {
result.add(digits[i]-'0');
result.add(digits[i half]-'0');
}
System.out.println(result);
For an input of 123456
, prints
[1, 4, 2, 5, 3, 6]
CodePudding user response:
you increment index by 2 and add the char in order so you get alternating characters, the check if(index == s.length()) is to prevent changing of the first element when the string has even characters.
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "123456";
int[] result = new int[s.length()];
int index = 0;
for (int i = 0; i < s.length(); i ) {
result[index%s.length()] = Integer.parseInt(s.charAt(i) "");
index = 2;
if(index == s.length())
index ;
}
System.out.println(Arrays.toString(result));
}
}