Moderate 不用比较符返回较大的数 @CareerCup
来源:互联网 发布:录屏软件画中画 编辑:程序博客网 时间:2024/04/30 12:07
通过判断a-b的最高位来知道哪一个数比较大
但是要注意overflow的情况
if a and b have different signs:// if a > 0, then b < <d, and k = l.// if a < 0, then b > 0, and k = 0.// so either way, k = sign(a)let k = sign(a)elselet k = sign(a - b) // overflow is impossible
但因为不能用if else所以用乘法来代替:
int k = use_sign_of_a * sa + use_sign_of_c * sc;
package Moderate;/** * Write a method which finds the maximum of two numbers. You should not use if-else or any other comparison operator.EXAMPLEInput: 5, 10Output: 10译文:写一个函数返回两个数中的较大者,你不能使用if-else及任何比较操作符。 * */public class S17_4 {/* Flips a 1 to a 0 and a 0 to a 1 */ public static int flip(int bit) { return 1 ^ bit; } /* Returns 1 if a is positive, and 0 if a is negative */ public static int sign(int a) { return flip((a >> 31) & 0x1); } public static int getMaxNaive(int a, int b) { int k = sign(a - b); int q = flip(k); return a * k + b * q; } public static int getMax(int a, int b) { int c = a - b; int sa = sign(a); // if a >= 0, then 1 else 0 int sb = sign(b); // if b >= 0, then 1 else 0 int sc = sign(c);// depends on whether or not a - b overflows /* We want to define a value k which is 1 if a > b and 0 if a < b. * (if a = b, it doesn't matter what value k is) */ int use_sign_of_a = sa ^ sb; // If a and b have different signs, then k = sign(a) int use_sign_of_c = flip(sa ^ sb); // If a and b have the same sign, then k = sign(a - b) /* We can't use a comparison operator, but we can multiply values by 1 or 0 */ int k = use_sign_of_a * sa + use_sign_of_c * sc; int q = flip(k); // opposite of k return a * k + b * q; } public static void main(String[] args) { int a = 26; int b = -15; System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b)); System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b)); a = -15; b = 2147483647; System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b)); System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b)); }}
- Moderate 不用比较符返回较大的数 @CareerCup
- CareerCup 17 中等难题 Q17.4 不用比较找出两数较大值
- Moderate Swap不用临时变量 @CareerCup
- 不用if-else和比较运算符,得出两个数中较大的那个数
- 不用任何比较判断找出两个数中较大的
- CI19.4-不用条件语句和比较操作符求两个数的较大值
- Moderate 阶层的结尾0个数 @CareerCup
- 用宏定义,不用?:和比较switch等求两个数中较大的数
- 不用任何比较判断找出两个数中较大的数
- 不用任何比较判断找出两个数中较大的数。
- Moderate 查单词 @CareerCup
- 比较两个数的较大数
- 比较两个数的较大数
- Moderate 判断井字游戏的胜利 @CareerCup
- 【刷题之路】不使用比较返回两个数中较大的值
- 比较两个数的较大值
- Moderate 整数打印读法 @CareerCup
- Moderate rand5()产生rand7() @CareerCup
- 嵌入式linux的网络编程(6)--多线程文件服务器
- 黑马程序员----Java概述
- 2013年12月2日 周一
- mongodb分布式集群架构
- 修改Ruby的config.yml文件
- Moderate 不用比较符返回较大的数 @CareerCup
- Spring整合ActiveMQ
- 【网络协议】HTTP协议笔记
- Erlang学习:MochiWeb + ERedis
- wcstombs 使用,支持中文档unicode
- An easy understanding on deep learning
- 读《阿里云是如何失控的》有感
- 中文分词-最长匹配法的实现
- Pthread(1)