题目描述:https://pycoder.blog.csdn.net/article/details/124852441
解法一:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ret = 0xfffff;
void dfs(int data, int times)
{
if (data == 1) {
ret = fmin(ret, times);
return;
}
if (data % 2 == 1) {
dfs((data - 1) / 2, times + 2);
dfs((data + 1) / 2, times + 2);
} else {
dfs(data / 2, times + 1);
}
}
int main(void)
{
int num;
scanf("%d", &num);
dfs(num, 0);
printf("%d\n", ret);
return 0;
}
解法二:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int dfs(int num, int times)
{
int ret;
if (num == 1) {
return times;
}
if (num % 2 == 0) {
ret = dfs(num / 2, times + 1);
} else {
int res1, res2;
res1 = dfs((num + 1) / 2, times + 2);
res2 = dfs((num - 1) / 2, times + 2);
ret = (res1 <= res2) ? res1 : res2;
}
return ret;
}
int main(void)
{
int n;
int ret;
scanf("%d", &n);
ret = dfs(n, 0);
printf("%d\n", ret);
return 0;
}