diff --git a/README.md b/README.md index c975348..702bd0c 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ continually updating 😃. * [13. Roman to Integer](src/0013_roman_to_integer/roman_to_integer.go)   *`string`* * [66. Plus One](src/0066_plus_one/plus_one.go)   *`array`* * [150. Evaluate Reverse Polish Notation](src/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go)   *`stack`* +* [258. Add Digits](src/0258_add_digits/add_digits.go)
diff --git a/src/0258_add_digits/add_digits.go b/src/0258_add_digits/add_digits.go new file mode 100644 index 0000000..246599c --- /dev/null +++ b/src/0258_add_digits/add_digits.go @@ -0,0 +1,41 @@ +/* +258. Add Digits +https://leetcode.com/problems/add-digits/ + +Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. +*/ +// time: 2019-01-07 + +package ad + +// time complexity: O( log num ) +// space complexity: O(1) +func addDigits(num int) int { + // num is a non-negative integer + for num > 9 { + num = performAdd(num) + } + return num +} + +func performAdd(num int) (res int) { + for num > 0 { + res += num % 10 + num /= 10 + } + return +} + +// time complexity: O(1) +// space complexity: O(1) +func addDigits1(num int) int { + /* + 0 1 2 3 4 5 6 7 8 9 + 0 1 2 3 4 5 6 7 8 9 + 10 11 12 13 14 15 16 17 18 19 + 1 2 3 4 5 6 7 8 9 10/1 + 20 21 22 23 24 25 26 27 28 29 + 2 3 4 5 6 7 8 9 10/1 11/2 + */ + return (num-1)%9 + 1 +} diff --git a/src/0258_add_digits/add_digits_test.go b/src/0258_add_digits/add_digits_test.go new file mode 100644 index 0000000..58aaa10 --- /dev/null +++ b/src/0258_add_digits/add_digits_test.go @@ -0,0 +1,19 @@ +package ad + +import "testing" + +func TestAddDigits(t *testing.T) { + num := 38 + expected := 2 + + testFuncs := []func(int) int{ + addDigits, + addDigits1, + } + + for _, function := range testFuncs { + if res := function(num); res != expected { + t.Errorf("expected %d, got %d", expected, res) + } + } +} diff --git a/src/README.md b/src/README.md index 0cbd1e7..38749dc 100644 --- a/src/README.md +++ b/src/README.md @@ -74,6 +74,7 @@ |0235|[235. Lowest Common Ancestor of a Binary Search Tree](0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go)|Easy|*`recursion; `* *`binary tree`*| |0237|[237. Delete Node in a Linked List](0237_delete_node_in_a_linked_list/dniall.go)|Easy|*`linked list`*| |0257|[257. Binary Tree Paths](0257_binary_tree_paths/binary_tree_paths.go)|Easy|*`binary tree`*| +|0258|[258. Add Digits](0258_add_digits/add_digits.go)|Easy|*`math`*| |0283|[Move Zeroes(solution1)](./0283_move_zeroes/move_zeroes.go)
[Move Zeroes(solution2)](./0283_move_zeroes/move_zeroes2.go)|Easy|*`array`*| |0300|[Longest Increasing Subsequence](./0300_longest_increasing_subsequence/lis.go)|Medium|*`dp`*| |0303|[303. Range Sum Query - Immutable](0303_range_sum_query/rsqim.go)|Easy||