30+ minutes - Sqrt(x)

Sqrt(x)


Implement int sqrt(int x).

Compute and return the square root of x.

先是用了一个 (int) Math.floor(Math.sqrt((double) x));

一分钟拿了个Accepted. 

然后花了十几分钟反编译 (A + B)^2 = A2 + 2AB + B2, 写了一个算法,数学逻辑的。carry nextbit等命名有点头晕,调试了十几分钟总算accept了。

public class Solution {
    public int sqrt(int x) {
        if (x <= 0) {
            return 0;
        }
        
        String str = String.valueOf(x);
        int result = 0;
        int carry = 0;
        int len = str.length();
        for (int i = 0; i < (len + 1) / 2; i++) {
            String first2 = str.substring(0, str.length() % 2 == 0 ? 2 : 1);
            str = str.substring(first2.length());
            int f2 = Integer.valueOf(first2);


            int nextBit = 0;
            for (int j = 1; j <= 10; j++) {
                if ((20 * result + j) * j > carry * 100 + f2) {
                    nextBit = j - 1;
                    break;
                }
            }
            carry = carry * 100 + f2 - (result * 20 + nextBit) * nextBit; 
            result = result * 10 + nextBit;
        }


        return result;
    }
}

最后想了想也挺傻的。其实完全可以投机取巧。
重新写了一个5分钟版本。区别其实说起来算法复杂度比那个数学算法还低,但是更多的依赖于Loop
public class Solution {
    public int sqrt(int x) {
        if (x <= 0) {
            return 0;
        }
        
        String str = String.valueOf(x);
        int result = 0;
        int len = str.length();
        int temp = 0;
        for (int i = 0; i < (len + 1) / 2; i++) {
            String next2 = str.substring(0, str.length() % 2 == 0 ? 2 : 1);
            str = str.substring(next2.length());
            int f2 = Integer.valueOf(next2);
            temp = temp * 100 + f2;
            int nextBit = 0;
            for (int j = 1; j <= 10; j++) {
                if ((result * 10 + j) * (result * 10 + j) > temp) {
                    nextBit = j - 1;
                    break;
                }
            }
            result = result * 10 + nextBit;
        }


        return result;
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值