LeetCode 258. Add Digits

    xiaoxiao2021-03-25  138

    题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

    For example:

    Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

    Follow up: Could you do it without any loop/recursion in O(1) runtime?

    思路: 其实就是如果这个数是0,返回0;这个数是9的倍数,直接返回9;若不是9的倍数,则返回它除9的余数。

    代码:

    class Solution { public: int addDigits(int num) { if(num==0){ return 0; } else if(num%9==0){ return 9; } else{ return num%9; } } };
    转载请注明原文地址: https://ju.6miu.com/read-11066.html

    最新回复(0)