Java Solution Add Digits


  • -1
    I
    public class Solution {
    public int addDigits(int num) {
     	int sum = sum(split(num));
    	while (sum >= 10) {
    	sum = sum(split(sum));}
    	return sum;
    
    }
    
    public static int[] split(int num) {
    	String x = Integer.toString(num);
    	int[] nums = new int[x.length()];
    	for (int i = 0; i < nums.length; i++) {
    		nums[i] = num % 10;
    		num /= 10;
    	}
    	return nums;
    }
    
    public static int sum(int[] a) {
    	int res = 0;
    	for (int i = 0; i < a.length; i++) {
    		res += a[i];
    	}
    	return res;
    }
    

    }


  • 0
    M

    One of the test cases seems to be wrong. For input 9, the expected output should be 9.


Log in to reply
 

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