Java O(1) Solution for Positive and Negative numbers


  • 16
    R

    Even though question asks answer for non-negative integer, this one works for +ve and -ve numbers.
    I referred this code on stackoverflow.

    Note: Negative numbers have digit sum as negative number. If positive digit sum needed for negative numbers then Math.abs() can be used while returning result.

    public class Solution {
        public int addDigits(int num) {
            return 1 + (num-1)%9;
        }
    }
    

  • 1
    C

    Nice code!

    This code will not work however for negative mutiples of 9 e.g. -9, -18 etc.

    Following simple modification of your code can work for all cases:

    public static int addDigitsAlt(int num) {
    if(num>=0) return 1 + (num-1)%9;
    else return - 1 + (num+1)%9;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.