-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path2544.交替数字和.java
77 lines (74 loc) · 1.25 KB
/
2544.交替数字和.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @lc app=leetcode.cn id=2544 lang=java
*
* [2544] 交替数字和
*
* https://leetcode.cn/problems/alternating-digit-sum/description/
*
* algorithms
* Easy (79.61%)
* Likes: 54
* Dislikes: 0
* Total Accepted: 32.7K
* Total Submissions: 41.1K
* Testcase Example: '521'
*
* 给你一个正整数 n 。n 中的每一位数字都会按下述规则分配一个符号:
*
*
* 最高有效位 上的数字分配到 正 号。
* 剩余每位上数字的符号都与其相邻数字相反。
*
*
* 返回所有数字及其对应符号的和。
*
*
*
* 示例 1:
*
*
* 输入:n = 521
* 输出:4
* 解释:(+5) + (-2) + (+1) = 4
*
* 示例 2:
*
*
* 输入:n = 111
* 输出:1
* 解释:(+1) + (-1) + (+1) = 1
*
*
* 示例 3:
*
*
* 输入:n = 886996
* 输出:0
* 解释:(+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0
*
*
*
*
* 提示:
*
*
* 1 <= n <= 10^9
*
*
*
*
*/
// @lc code=start
class Solution {
public int alternateDigitSum(int n) {
int sign = 1, sum = 0;
while (n > 0) {
int digit = n % 10;
sum += sign * digit;
sign = -sign;
n /= 10;
}
return -sign * sum;
}
}
// @lc code=end