zoukankan      html  css  js  c++  java
  • 剑指offer:求1+2+..+n

    题目描述

    求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
    一,利用利用短路 && 来实现 if的功能;
    二,利用递归来实现循环while的功能
     
    递归(使用&&的短路性质)
    class Solution {
    public:
        int Sum_Solution(int n) {
            int ans = n;
            ans&&(ans += Sum_Solution(ans-1));
            return ans;
        }
    };

     不使用乘法求乘法:

    把a拆成2的幂的和,a = 2^e0 + 2^e1 + 2^e2.... 

    a * b = (2^e0 + 2^e1 + 2^e2+...) * b 
                  = b * 2^e0 + b * 2^e1 + b * 2^e2 + ...
                 = (b << e0) + (b << e1) + ....
    利用循环求n*(n-1)/2
     
    int Sum_Solution(int n) {
        int a = n;
        int b = n+1;
        int result = 0;
        while(a){
            if(a&1){
                result += b;
            }
            a = a>>1;
            b = b<<1;
        }
        return result>>1;
    }
    class Solution {
    public:
        int Sum_Solution(int n) {
            int result = Sum_Solution(n,n+1);
            return result>>1;
        }
        int Sum_Solution(int a,int b) {
            int sum = 0;
            (a&1 == 1) && (sum += b);
            (a!=0) &&  (sum += Sum_Solution(a>>1,b<<1));
            return sum;
        }
    };
     
  • 相关阅读:
    render()中添加js函数
    切图相关记录
    Jenkins 配置代理。
    Ant 打包 web 项目 xml 模板
    linux 删除命令
    git 创建 本地 裸 仓库
    swagger spring-boot 配置
    Idea 根据 表 生成 实体类
    java 流 api
    spring eureka 注册显示 ip:端口号
  • 原文地址:https://www.cnblogs.com/ttzz/p/13933915.html
Copyright © 2011-2022 走看看