2544. Alternating Digit Sum

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

  .spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;}

Solution (Java)

class Solution {
    public int alternateDigitSum(int n) {
        String s=Integer.toString(n);
        // char ch[]=s.toCharArray();
        int res=0,r1=0,r2=0;
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            if(i%2==0)
            {
                r1=r1+(c-'0');
            }
            else if(i%2!=0)
            {
                r2=r2-(c-'0');
            }
        }
        res=r1+r2;
        return res;
    }
}

Explain:

nope.

Complexity: