Reputation: 11
i want to reverse every odd pair of strings and them add them together with the even pair.
for example the string 123456789 would turn into 213465789 and then adding them together would give 21+34+65+78+9 which = 207.
my current code is
public static void main(String[] args) {
String Num = "123456789";
System.out.println(reverse(Num) + ".");
}
public static int reverse(String a) {
String newa = "";
String revString = "";
char ch;
for (int i = 0; i < a.length(); i=i+4) {
newa = (a.substring(i, i + 2));
ch = newa.charAt(i);
revString = ch + revString;
}
}
I do have an general idea which is to reverse every second pair of strings and place them back into a new string that would be "213465789". Then split the string into pairs and add them up and whatever other operation like /, * and % but i cant seem to write my code
Thanks in advance
Upvotes: 0
Views: 297
Reputation: 15891
Simply algo would be something like
String Num = "123456789";
Loop for(int i= 0 to n-3;i=i+2) - to reverse the string
swap i
with i+1
- this give alternate rev string
again for(int i= 0 to n-3;i=i+2)
- to add the sum
sum = sum + ((chatAt(i)-'0')*10+(charAt(i+1)-'0'))
- typecast from char
to int
using [char]-'0'
logic, for String "21", logic would be to have (2*10+1)
Upvotes: 0
Reputation: 41200
try this -
int pairCout=0;
int sum =0;
for (int i = 0; i < a.length();i+=2) {
String newa = a.substring(i, (i + 2)<a.length()?(i+2):a.length());
pairCout++;
if(pairCout%2 ==0){ // EVEN/ODD separation
String reverse = new StringBuilder(newa ).reverse().toString();
sum+=Integer.parseInt(reverse); // SUMMATION
}else{
sum+=Integer.parseInt(newa ); // SUMMATION
}
}
Just an approach - OUTPUT - 207
Upvotes: 1