All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2501_2600.s2544_alternating_digit_sum.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g2501_2600.s2544_alternating_digit_sum;

// #Easy #Math #2023_05_11_Time_0_ms_(100.00%)_Space_39.4_MB_(79.49%)

/**
 * 2544 - Alternating Digit Sum\.
 *
 * Easy
 *
 * 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
**/
public class Solution {
    public int alternateDigitSum(int n) {
        String s = Integer.toString(n);
        char[] arr = s.toCharArray();
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
            res += (int) Math.pow(-1, i) * (arr[i] - '0');
        }
        return res;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy