字节8.29笔试 求问
字节第一题,两个数每次加i(i从1开始),得到两数相等的最小计算次数。
找规律找到如果两数差值是斐波那契数那就直接返回斐波那契数列的长度;如果不是则返回上一个斐波那契数k的长度+(差值-k)*2
有大佬看看这个思路哪里错了吗...只过了50%……
差值对应计算次数如下:
1 2 3 4 5 6 7 8 9 10 ...
1 3 2 4 6 3 5 7 9 4 ....
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
int[] res = new int[count];
for(int i = 0;i < count;i ++){
int a = scanner.nextInt();
int b = scanner.nextInt();
res[i] = solve(a,b);
}
for(int i = 0;i < count;i ++){
System.out.println(res[i]);
}
}
public static int solve(int a,int b){
if(a==b) return 0;
//???????????
int flag = Math.abs(a-b);
int count =0, i= 1, pre = 0;
while(count<flag){
pre = count;
count += i;
if(count==flag) return i;
else if(count>flag) break;
else if(count<flag) i++;
}
return (i-1)+(flag-pre)*2;
}
} #字节跳动笔试##字节跳动#
海康威视公司福利 1382人发布
