Reputation: 73
I want to calculate the sum of all integers in an array which contain two digits. For example:
int[] arr1 = {1, 23, 4, 55};
int[] arr2 = {2, 5, -66, 23};
The result for the first array should be 23 + 55 = 78
, while the result for the second array should be -66 + 23 = -43
. How can I achieve this?
Upvotes: 0
Views: 14532
Reputation: 11
You can use java 8 streams.
Here k is the integer array given in the question:
Arrays.stream(k).filter(p->(Math.abs(p)>9 && Math.abs(p<100)).sum();
Upvotes: 0
Reputation: 1
Runnable code can be downloaded from https://github.com/sankarees/playground/blob/main/calculate-the-sum-of-all-two-digits-integers-in-an-array
Snipper code:
public static int getSumOfTwoDigits(int[] numbers) {
int sum = 0;
for (int number : numbers) {
int divident = (number < 0 ? number * -1 : number) / 10;
if (divident > 0 && divident < 10) {
sum += number;
}
}
return sum;
}
Upvotes: 0
Reputation: 3540
You can convert to string and check.
for(int num : v) {
// check for size
string str = to_string(num);
if( (str.size() == 2) || (str.size()==3 && (str[0]=='+' || str[0]=='-') ) )
sum += num;
}
cout<<sum;
Upvotes: 0
Reputation: 181
To get the sum of two numbers in an array:
Keep in mind that when calling an array to access a stored value, use the index (or position) of the value within the array — then add one. We use this formula of indexOfValue + 1 as most languages start indexing arrays at the 0th position (although this is not always true, for example, Fortran indexes its arrays beginning with 1. So ‘integer anArray(50)’ would create an array capable of storing 50 int elements, starting at index 1 and ending at index 50). Another consequence of this structural design within programming languages is that the last value of an array can be accessed using sizeOfArray - 1.
To clarify these concepts, look at this code:
int[] a = {1,23,4,55};
int firstSum = a[1] + a[3]; // performs 23 + 55
int[] b = {2,5,-66,23};
int secondSum = b[2] + b[3]; // performs -66 + 23
int sumOfLastValues = a[a.length - 1] + b[b.length - 1];
Upvotes: 2
Reputation: 27
I will give you some code I have tried for it:
int sum1 = 0, sum2 = 0;
int[] arr1 = {1, 23, 4, 55};
for(int i: arr1){
if(i/10 > 0 && i/100 == 0){
sum1 += i;
}
else if(i/-10 > 0 && i/-100 == 0){
sum1 -=i;
}
}
int[] arr2 = {2, 5, -66, 23};
for(int i: arr2){
if(i/10 > 0 && i/100 == 0){
sum2 += i;
}
else if(i/-10 > 0 && i/-100 == 0){
sum2 +=i;
}
}
System.out.println(sum1);
System.out.println(sum2);
The results are:
78
-43
Upvotes: 0
Reputation: 663
If you want to sum the elements which contain two digits only, you could use the following:
int[] arr = {1, 23, 4, 55};
int sum = 0;
for (int i : arr) {
if (Math.abs(i) > 9 && Math.abs(i) < 100) {
sum += i;
}
}
Upvotes: 8