计算1+2+3+...+n;不许用乘除法和if、 while、switch、for等关键字计算
来源:互联网 发布:幼儿园大班美工活动 编辑:程序博客网 时间:2024/05/16 10:52
今天在群里看到有人发了一个问题,问题出自(一家公司的笔试面试题),当时第一眼看到时还感觉有点意思,随后经过分析琢磨想到了一种解法:
三元操作符也称条件操作符,它显得比较特别,因为它有三个操作数,但它确实不属于操作符的一种,因为它最终也会生成一个值。
boolean-exp?value0 :value1;
如果boolean-exp为true就计算value0否则计算value1
如果你打算频繁使用,还是多考虑下,它容易产生可读性极差的代码
好了,不说了,直接上代码了:
public class TestSum { //不使用乘除法和if、 while、switch、for等关键字计算 private static int sum(int i) { return i==1? i:i+sum(i-1); } //使用if计算 private static int num(int n){ if(n==1){ return n; }else{ return n+num(n-1); } } public static void main(String[] args){ int n1=TestSum.sum(100); System.out.println(n1); int n2=TestSum.num(100); System.out.println(n2); }}
sum结果:5050num结果:5050
0 0
- 计算1+2+3+...+n;不许用乘除法和if、 while、switch、for等关键字计算
- 求解1+2+3+...+n,要求不能使用乘除法、while、for、if 、else、switch、case等关键字
- 求1+2+…+n.要求不能使用乘除法、for、while、if、else、switch、case等关键字
- 一道面试题:求1+2+…+n,不使用乘除法、for、while、if 、else、switch、case 等关键字
- 求1+2+…+n(要求不能使用乘除法、for、while、if、else、switch、case等关键字)
- 求1+2+...+n的前n项和,但不用乘除法、for、while、if、else、switch、case等关键字及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求 1+2+3+..n不能使用乘除法、 for 、 while 、 if 、 else 、 switch 、 case 等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
- 求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。Java实现
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
- CentOS 6.5 LVS + KeepAlived 搭建 负载均衡 高可用 集群
- mongoDB 3.0 安全权限访问
- XML CDATA的作用
- Altium designer小技巧记录
- serializable 类 XXXX 未声明类型为 long 的静态终态 serialVersionUID 字段
- 计算1+2+3+...+n;不许用乘除法和if、 while、switch、for等关键字计算
- spring 笔记4 BeanDefinitionReader
- 278. First Bad Version*
- MySQL5.7绿色安装及问题
- elasticsearch初入门
- 【NOI2014】魔法森林
- C++ const和static
- 网络编程7
- JavaScript系列文章:详解正则表达式之一