每日一练0

1.A+B问题

描述:给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

说明:

a和b都是 32位 整数么?

  • 是的

我可以使用位运算符么?

  • 当然可以

错误代码:(很难发现的bug;a=6,b=-5时出错)

 public class Solution {
    public int aplusb(int a, int b) {
        if(a == -b){
            return 0;
        }else{

            // 位运算
            return (a^b)|((a&b)<<1);
        }
    }
};

通过代码:

public class Solution {
    public int aplusb(int a, int b) {  
        if(a==0) return b;  //不再进位
        if(b==0) return a;  //不进位操作为零,直接取进位操作的结果
        int sum,i;  
        i=a^b; //不进位相加的结果 
        sum=(a&b)<<1;  //进位的结果
        return aplusb(sum,i); // 递归,两者再进行相加
    }  
}

 

2.尾部的零

描述:设计一个算法,计算出n阶乘中尾部零的个数

说明:时间复杂度为O(logN)

通过代码:

public class Solution {
    public long trailingZeros(long n) {
        long count0 = 0;
        for(int i = 1;Math.pow(5,i)<=n;i++){
            count0 += n/(long)Math.pow(5,i);
        }
        return count0;
    }

}

总结:

(1).数学方法计算阶乘尾部的零

参考:http://blog.163.com/taoqibao_tao/blog/static/122906690200962784627562/

(2).Math.pow(5,i); // 计算以5为底,i为指数的值

 

3.统计数字

描述:计算数字k在0到n中的出现的次数,k可能是0~9的一个值

样例:

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

通过代码:

public class Solution {
    public int digitCounts(int k, int n) {
        int count = 0; //计数器
        int i = 0; // 遍历的中间变量
        for(;i<=n;i++){
            if(Integer.toString(i).contains(Integer.toString(k))){
                if(Integer.toString(i).length() == 1){
                    count += 1;
                }else{
                    for(int j=1;j<=Integer.toString(i).length();j++){

                        // 设整数i长度为m,则i除以m-1次方取模10得到最高位的值,依次类推可得i各个位的值
                        if(Integer.toString((i/(int)Math.pow(10, j-1))%10).contains(Integer.toString(k))){
                            count += 1;
                        }
                    }
                }
            }
        }
        return count;
    }
}

 

4.丑数Ⅱ

描述:设计一个算法,找出只含素因子235 的第 n 小的数。

符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

注意事项:我们可以认为1也是一个丑数

样例:如果n=9,返回10

挑战:要求时间复杂度为O(nlogn)或者O(n)

通过代码:

public class Solution {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int num_2 = 0;
        int num_3 = 0;
        int num_5 = 0;
        for(int i=1;i<n;i++){
            ugly[i] = Math.min(Math.min(ugly[num_2]*2, ugly[num_3]*3),ugly[num_5]*5);
            if(ugly[i]/ugly[num_2] == 2){
                num_2++;
            }
            if(ugly[i]/ugly[num_3] == 3){
                num_3++;
            }
            if(ugly[i]/ugly[num_5] == 5){
                num_5++;
            }
        }
        return ugly[n-1];
    }
}

参考链接:http://blog.csdn.net/lhanchao/article/details/52079323

 

转载于:https://my.oschina.net/u/3450072/blog/1588207

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值