[LeetCode]136. Single Number

来源:互联网 发布:淘宝商品被删除怎么办 编辑:程序博客网 时间:2024/06/16 15:18

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 = 111 + 1 = 2. Since 2 has only one digit, return it



1版:

将该数一直对10取余数,之和相加。

(6ms)

class Solution {public:int addDigits(int num) {int sum = 0;while (num > 0){sum += num % 10;num /= 10;}if (sum < 10)return sum;return addDigits(sum);}};


2:简化1

(3ms)

class Solution {public:int addDigits(int num) {while (num >= 10) {num = (num / 10) + num % 10;}return num;}};


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

class Solution {public:    int addDigits(int num) {        return num-9*((num-1)/9);    }};


0 0
原创粉丝点击