本文共 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/