0
点赞
收藏
分享

微信扫一扫

笔试算法《杨辉三角的变形》


描述

笔试算法《杨辉三角的变形》_python

以上三角形的数阵,第一行只有一个数1,以下每行的每个数,是恰好是它上面的数,左上角数到右上角的数,3个数之和(如果不存在某个数,认为该数就是0)。

求第n行第一个偶数出现的位置。如果没有偶数,则输出-1。例如输入3,则输出2,输入4则输出3。

输入n(n <= 1000000000)
本题有多组输入数据,输入到文件末尾,请使用while(cin>>)等方式读入
输入描述:
输入一个int整数

输出描述
输出返回的int值

示例1
输入:
4
2

输出
3
-1

代码

public class Huawei杨辉三角的变形 {

/**
* 1,观察规律,多写几行
* 偶数出现在前四个数
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while ((str = br.readLine()) != null) {
int n = Integer.parseInt(str);
System.out.println(getResult(n));
}
}

public static int getResult(int i) {
if (i <= 2) {
return -1;
} else if (i % 2 == 1) {
return 2;
} else {
if (i % 4 == 0) {
return 3;
} else {
return 4;
}
}
}
}


举报

相关推荐

0 条评论