number-of-steps-to-reduce-a-number-to-zero
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
給定一個正整數 num
依據以下的法則num遞減到 0
1 如果 num 是偶數 則讓 num = num/2
2 如果 num 不是偶數 則讓 num = num -1
寫一個function 計算出所需要的步驟數目
首先是需要把每個步驟利用一個counter記錄下來
每做一步 把 counter加一
Given an integer num, num > 0
step 1: set a integer count = 0
step 2: check if num == 0 go to step 6
step 3: check if num is even , num = num /2
step 4: check if num is not even, num = num - 1
step 5: count = count + 1 go to step 2
step 6: return count
因為英文不是筆者母語
所以在題意解讀上 容易被英文用詞解讀給搞模糊
一開始不習慣把pseudo code寫下來
因此 不太容易把自己的code做解析
對於table driven test還不太熟析
所以對於寫test還是耗費不少時間
package number_of_steps
func numberOfSteps(num int) int {
count := 0
for num > 0 {
if num%2 == 0 {
num = num / 2
} else {
num -= 1
}
count++
}
return count
}
package number_of_steps
import "testing"
func Test_numberOfSteps(t *testing.T) {
type args struct {
num int
}
tests := []struct {
name string
args args
want int
}{
{
name: "Example1",
args: args{
num: 14,
},
want: 6,
},
{
name: "Example2",
args: args{
num: 8,
},
want: 4,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := numberOfSteps(tt.args.num); got != tt.want {
t.Errorf("numberOfSteps() = %v, want %v", got, tt.want)
}
})
}
}
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing