一.原题
链接:Training on Progressive Spiral Number Position | Codewars
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: |
二、解题
1、分析
(1)数字必须存入点组成的正方形中。
(2) 5个数字可用3X3存放,6个必须用4X4。可用下面印证
layers(1) === 1 layers(5) === 2 layers(25) === 3 layers(30) === 4 layers(50) === 5 |
2、思路
(1)N行N列点阵,最外行有2*N-1个点 |
(2)N行N列点阵,共有pow(2*N-1,2)个点 |
(3)若pow(2*N-1,2)恰巧>=输入值,则返回N即可 |
三、Myway
int layers(int n) {
// <---- hajime!
for(int i=1;;i++){
if((2*i-1)*(2*i-1)>=n) return i;
}
}