Interview Check If n Is A Perfect Square
来源:互联网 发布:手机遥控器软件安卓版 编辑:程序博客网 时间:2024/05/07 08:29
Check if a given number is a perfect square with only addition or substraction operation.
eg. 25 returns true; 19 returns false.
Perfect square number 有一个特性,比如0,1,4,9,16,25 他们之间的间隔分别是1,3,5,7,9,每次间隔都是i+2.
所以每次往下减i, i 更新成i+2. 看最后结果是否为0即可。
import java.util.*;public class isPerfectSquare{public static void main(String [] args){int num1 = 0;int num2 = 1;int num3 = 25;int num4 = 19;System.out.println(isPerfectSquare(num1));System.out.println(isPerfectSquare(num2));System.out.println(isPerfectSquare(num3));System.out.println(isPerfectSquare(num4));}private static boolean isPerfectSquare(int n){//1,4,9,16,25//1+3+5+7+9if(n<0){return false;}int i = 1;while(n>0){n-=i;i+=2;}if(n == 0){return true;}else{return false;}}}
0 0
- Interview Check If n Is A Perfect Square
- How to check if a Number is Positive or Negative in Java - Interview Question
- A Square Perfect Square
- Check if a string value is numeric
- Check if a linked list is palindrome
- Q2.7 Check if a list is a palindrome
- CareerCup Find whether a given number is a perfect square or not.(Addition and Subtraction only)
- Check if a File is in Internet Explorers Cache
- Check if a given Binary Tree is SumTree
- Q1.8 Check if s2 is a rotation of s1
- Q4.5 Check if a binary search is BST
- Check if object is array?
- 2.7 Implement a function to check if a linked list is a palindrome
- Check if a port is being used on a Windows machine
- How To: Check if a user is part of a SharePoint group in InfoPath
- A program to check if a binary tree is BST or not
- Q4.1 Implement a function to check if a tree is balanced
- (SOJ) check if a word is on a given Boggle board
- 聚合函数
- Spring MVC form handling annotation example
- 数据库练习3
- 数据库练习4
- 数据库练习4
- Interview Check If n Is A Perfect Square
- 胡思 胡写(非技术文章)
- 固定布局的几种方式
- Handling duplicate form submission in Spring MVC
- Spring MVC RedirectView example
- Developing SOAP Web service using Apache CXF
- 【Linux探索之旅】第三部分第二课:流、管道、重定向,三管齐下
- 关于removeFromSuperview关键的几个点
- 分享一个Linux下安装ASM+ORACLE的自动化脚本(四)