-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalternating_digit_sum.cpp
More file actions
54 lines (36 loc) · 969 Bytes
/
Copy pathalternating_digit_sum.cpp
File metadata and controls
54 lines (36 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//question//
You are given a positive integer n. Each digit of n has a sign according to the following rules:
The most significant digit is assigned a positive sign.
Each other digit has an opposite sign to its adjacent digits.
Return the sum of all digits with their corresponding sign.
Example 1:
Input: n = 521
Output: 4
Explanation: (+5) + (-2) + (+1) = 4.
Example 2:
Input: n = 111
Output: 1
Explanation: (+1) + (-1) + (+1) = 1.
Example 3:
Input: n = 886996
Output: 0
Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
Constraints:
1 <= n <= 109
//solution//
class Solution {
public:
int alternateDigitSum(int n) {
int sum = 0;
string s = to_string(n);
for(int i=0;i<s.size();i++){
if(i%2==0){
sum += s[i]-'0';
}
else{
sum -= s[i]-'0';
}
}
return sum;
}
};