programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Alternating Sum of a number

Petar Stoyanov
Greenhorn
Posts: 21
I'm having trouble understanding/figuring out how i'm supposed to code the alternating sum of an inputed number /I suppose as in int??/

The code is supposed to take a number lets say 4321 and alternate + and - between the numbers. It can start either with - or + which really throws me off

there are 2 shown inputs and expected outputs as an example:
input1= 101 => output1= 2 , we take  +1-0+1=2
input2= 42 => output2= -2 , which should mean we take the first number as "-" => -4+2=-2

I'm really in a pinch here and i've got no idea what to do ;/

Piet Souris
Master Rancher
Posts: 2044
75
Is your question related in any way to this topic:
https://coderanch.com/t/672251/java/Find-number-minimum-operations-number

Petar Stoyanov
Greenhorn
Posts: 21
As far as i can see he has the expected output and must figure out what signs to have between 1,2,3,4,5,6... to get to that expected output the fastest
i just have random input numbers 231,412,51... and can get 2 outputs basicly - 1 starting from + then - and alternating or starting from - and then + and so on.
I have to brake down a number ex. 231 into 2,3,1 and then alternate +,- between them

Sergiu Dobozi
Ranch Hand
Posts: 107
2
My two cents as a beginner in programming.

Input 1 takes 1234.
Do while number is not 0
{1234%10=4.
Store 4 in the array with length arraylength=(int)(Math.log10(n)+1).
1234=1234/10}
for(i=0;i<arraylength;i++)
//create a sum where you alternate the sign using a variable which assigns itself - for iteration 1 and back to + to iteration 2.

Do almost the same for the second output.

Junilu Lacar
Sheriff
Posts: 11494
180
To alternate the sign, use these basic math facts:

If you have a variable, sign, you can easily flip it between -1 and +1 using the above.

Campbell Ritchie
Marshal
Posts: 56562
172
You can “randomly” start with a different sign like this:-The () are redundant, but it is often worth using () around ?: because it has a low precedence. Another way to swap signs is like this:-The () are again redundant.

 It is sorta covered in the JavaRanch Style Guide.