Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 989025d

Browse files
solves #2544: Alternating Digit Sum in java
1 parent 4e0c2f8 commit 989025d

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,7 @@
796796
| 2529 | [Maximum Count of Positive Integer and Negative Integer](https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer) | [![Java](assets/java.png)](src/MaximumCountOfPositiveIntegerAndNegativeInteger.java) | |
797797
| 2535 | [Difference Between Element Sum and Digit Sum of an Array](https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array) | [![Java](assets/java.png)](src/DifferenceBetweenElementSumAndDigitSumOfAnArray.java) | |
798798
| 2540 | [Minimum Common Value](https://leetcode.com/problems/minimum-common-value) | [![Java](assets/java.png)](src/MinimumCommonValue.java) | |
799-
| 2544 | [Alternating Digit Sum](https://leetcode.com/problems/alternating-digit-sum) | | |
799+
| 2544 | [Alternating Digit Sum](https://leetcode.com/problems/alternating-digit-sum) | [![Java](assets/java.png)](src/AlternatingDigitSum.java) | |
800800
| 2549 | [Count Distinct Numbers on Board](https://leetcode.com/problems/count-distinct-numbers-on-board) | | |
801801
| 2553 | [Separate the Digits in an Array](https://leetcode.com/problems/separate-the-digits-in-an-array) | | |
802802
| 2558 | [Take Gifts From the Richest Pile](https://leetcode.com/problems/take-gifts-from-the-richest-pile) | | |

‎src/AlternatingDigitSum.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// https://leetcode.com/problems/alternating-digit-sum
2+
// T: O(log(n))
3+
// S: O(1)
4+
5+
public class AlternatingDigitSum {
6+
public int alternateDigitSum(int n) {
7+
final String number = n + "";
8+
int sum = 0;
9+
for (int index = 0, parity = 1 ; index < number.length() ; index++, parity *= -1) {
10+
sum += parity * (number.charAt(index) - '0');
11+
}
12+
return sum;
13+
}
14+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /