博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer CalCarryBit 计算进位个数
阅读量:4207 次
发布时间:2019-05-26

本文共 1416 字,大约阅读时间需要 4 分钟。

题目描述:

计算两个整数相加时需要进行多少次进位 假设输入的整数都不超过9个数字

思路:

使用一个变量carry保存进位,一个变量count保存相加次数,每次将两个数的个位进行相加,大于10则count自增,注意每次将数和10取余就可以取到个位的数

方法一:

public static int calCarryNum(int num1, int num2) {        if (num1 == 0 && num2 == 0) {            return -1;        }        //每次mod 10就可以取到个位        int carry = 0;        int count = 0;        int temp = 0;        while (num1 != 0 && num2 != 0) {            temp = num1 % 10 + num2 % 10 + carry;            if (temp >= 10) {                count++;                carry = temp - 10;            }            num1 = (num1-num1%10)/10;            num2 = (num2-num2%10)/10;        }        return count;    }

方法二:

public static int calCarryBit(int num1, int num2) {        if (num1 == 0 && num2 == 0) {            return -1;        }        int num1Bit = countBit(num1);        int num2Bit = countBit(num2);        int temp = Math.min(num1Bit, num2Bit);        int carry = 0;        int count = 0;        for (int i = 0; i < temp; i++) {            int result = calBitNum(num1, i) + calBitNum(num2, i) + carry;            if (result >= 10) {                count++;                carry = result - 10;            }        }        return count;    }    /**     * 计算一个整数的位数     */    public static int countBit(int number) {        int count = 1;        int temp = number / 10;        while (temp != 0) {            count++;            temp = temp / 10;        }        return count;    }

转载地址:http://dhqli.baihongyu.com/

你可能感兴趣的文章
手动12 - 安装php加速器 Zend OPcache
查看>>
set theme -yii2
查看>>
yii2 - 模块(modules)的view 映射到theme里面
查看>>
yii2 - controller
查看>>
yii2 - 增加actions
查看>>
网站加载代码
查看>>
php图像处理函数大全(缩放、剪裁、缩放、翻转、旋转、透明、锐化的实例总结)
查看>>
magento url中 uenc 一坨编码 base64
查看>>
强大的jQuery焦点图无缝滚动走马灯特效插件cxScroll
查看>>
Yii2.0 数据库查询
查看>>
yii2 db 操作
查看>>
mongodb group 有条件的过滤组合个数。
查看>>
yii2 用命令行操作web下的controller
查看>>
关于mongodb的 数组分组 array group
查看>>
MongoDB新的数据统计框架介绍
查看>>
mongodb fulltextsearch 关于语言的设置选项
查看>>
mongodb 增加全文检索索引
查看>>
symfony
查看>>
yourls 短连接 安装
查看>>
yii2 php namespace 引入第三方非namespace库文件时候,报错:Class not found 的解决
查看>>