• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

M面经Prepare: Find integer Average of 2 integers.

The definition of integer average is the highest smaller integer if average is floating point number. Also the condition if that they can not use any typecasting or any datatype other than int.

Example: a = 4, b = 5, avg = 4 a = 4, b = 6, avg = 5 a = -4, b = -6, avg = -5 a = 4, b = -5, avg = -1 a = -4, b = -5, avg = -5

-9%2 == -1 不是1, 所以负数%2==1不是奇数判定标准。但是偶数标准仍是%2 == 0

 1 package FindIntegerAverage;
 2 
 3 public class Solution {
 4     public int aver(int a, int b) {
 5         if ((a+b)%2 == 0)return (int)(a+b)/2;
 6         else return (int)(a+b-1)/2;
 7     }
 8 
 9     /**
10      * @param args
11      */
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         Solution sol = new Solution();
15         int res = sol.aver(-4, -5);
16         System.out.print(res);
17     }
18 
19 }

 

posted @ 2016-02-16 11:56  neverlandly  阅读(400)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3