不用加减乘除做加法__牛客网
目录
不用加减乘除做加法__牛客网
链接:不用加减乘除做加法__牛客网
来源:牛客网
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
数据范围:两个数都满足 −10≤n≤1000-10 \le n \le 1000−10≤n≤1000
思路:
利用异或^和与&运算进行。
代码实现:
public class Solution {
public int Add(int num1,int num2) {
int ret = num1 ^ num2;//处理00 01 10
int temp = (num1 & num2) << 1; //处理进位
while(temp != 0){
int retp = ret;
ret = ret ^ temp;
temp = (retp & temp) << 1;
}
return ret;
}
}
三角形__牛客网
链接:三角形__牛客网
来源:牛客网
给定三条边,请你判断一下能不能组成一个三角形。
输入描述:
输入包含多组数据,每组数据包含三个正整数a、b、c(1≤a, b, c≤10^100)。
输出描述:
对应每一组数据,如果它们能组成一个三角形,则输出“Yes”;否则,输出“No”。
思路:
题目中已说明,数值范围在1到10的100次方,此时已超过long类型的最大范围。因此需要使用BigInteger类型来解决该问题。
解决步骤:
1.引入BigInteger类 import java.math.BigInteger;
2.用nextBigInteger()方法去接收数值
3.用add()方法进行相加
4.用compareTo()方法进行比较大小,返回值为int类型
代码实现:
import java.util.Scanner;
import java.math.BigInteger;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextBigInteger()){
BigInteger a = scanner.nextBigInteger();
BigInteger b = scanner.nextBigInteger();
BigInteger c = scanner.nextBigInteger();
if((a.add(b)).compareTo(c) > 0 && (b.add(c)).compareTo(a) > 0
&& (a.add(c)).compareTo(b) > 0){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
扩充一些方法:
-
add(BigDecimal)
BigDecimal对象中的值相加,返回BigDecimal对象
-
subtract(BigDecimal)
BigDecimal对象中的值相减,返回BigDecimal对象
-
multiply(BigDecimal)
BigDecimal对象中的值相乘,返回BigDecimal对象
-
divide(BigDecimal)