网易笔试题_优雅的点

题目:

小易有一个圆心在坐标原点的圆,小易知道圆的半径的平方。小易认为在圆上的点而且横纵坐标都是整数的点是优雅的,小易现在想寻找一个算法计算出优雅的点的个数,请你来帮帮他。
例如:半径的平方如果为25
优雅的点就有:(+/-3, +/-4), (+/-4, +/-3), (0, +/-5) (+/-5, 0),一共12个点。
输入描述:
输入为一个整数,即为圆半径的平方,范围在32位int范围内。

输出描述:
输出为一个整数,即为优雅的点的个数

输入例子1:
25

输出例子1:
12

 

Java简单实现:

 1 package interview.test;
 2 
 3 import sun.util.resources.CalendarData_uk;
 4 
 5 import java.util.Scanner;
 6 
 7 /**
 8  * Created by BUAA514 on 2018-08-10.
 9  */
10 public class NetTest2 {
11 
12     /**
13      * 简单思路:算出半径,然后从0开始,到半径的各个数,计算平方和是否满足,满足条件更新计数,
14      * 否则,更行下一轮计算的首尾位置,首++;尾=根号下(输入数-首*首)
15      * 注意:更新计数时,当坐标满足一个坐标等于0时或者两个坐标值相等时,计数+4。
16      */
17 
18     private static int count = 0;
19     public static void main(String[] args) {
20         Scanner sc = new Scanner(System.in);
21         int inputNum = sc.nextInt();
22         int end = (int)Math.sqrt(inputNum);
23         Calculate(inputNum,0,end);
24         System.out.println(count);
25     }
26 
27     private static void Calculate(int inputNum, int start, int end) {
28 
29         while(start <= end) {
30             if (start*start + end*end == inputNum) {
31                 if (start == 0 || start == end) count += 4;
32                 else count+=8;
33             }
34             start++;
35             end = (int)Math.sqrt(inputNum - start*start);
36         }
37 
38         // 刚开始使用递归调用,栈溢出,80%
39         /*if(start <= end) {
40             if (start*start + end*end == inputNum) {
41                 if (start == 0 || start == end) count += 4;
42                 else count+=8;
43             }
44             start++;
45             end = (int)Math.sqrt(inputNum - start*start);
46             Calculate(inputNum,start,end);
47         }*/
48     }
49 }

 

posted @ 2018-08-10 17:16  一介草民李八千  阅读(195)  评论(0编辑  收藏  举报