The Indian Engineer

Problem 2544 Alternating Digit Sum

Posted on Last edited 2 mins

Math String

Problem Statement

Link - Problem 2544

Question

You are given a positive integer n. Each digit of n has a sign according to the following rules:

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

Solution

class Solution {
public:
    int alternateDigitSum(int n) {
        string num = to_string(n);
        int var = 0, sign = 1;
        for(int i = 0; i< num.size(); i++){
            var += (num[i]-'0')*sign;
            sign*=-1;
        }
        return var;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
String conversion O(log(n)) O(1)
Computation O(log(n)) O(1)

Explanation

1. Intuition

2. Implementation