GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leet-code/Java/Add Digits.java at master · awangdev/leet-code Expand file tree/ Copy pathAdd Digits.javaMore file actions executable file ·48 lines (40 loc) · 1.14 KB / Copy pathAdd Digits.javaFile metadata and controlsexecutable file ·48 lines (40 loc) · 1.14 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 E 1519709532 tags: Math 方法1: 普通做法就是按照题意, double-while loop把数字加起来. 第一层循环是O(n), 然后第二层循环就少很多数位, overall O(n) 方法2: 找数学规律, 每过9个数字, 取mod就会开始重复, 所以给所有数字取mod 就可以间接找到答案. O(1) ``` /* 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? */ /* Thoughts: Keep adding until result < 10 Double-while loop: start with a num, calculate result, then num = result. */ class Solution { public int addDigits(int num) { if (num < 10) { return num; } while (num > 9) { int temp = 0; while (num != 0) { temp += num % 10; num = num / 10; } num = temp; } return num; } } class Solution { public int addDigits(int num) { return (num - 1) % 9 + 1; } } ``` |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |