您的位置:首页 > 编程语言 > Go语言

Algorithm: 计算类题目归类整理

2018-03-25 03:10 169 查看
提纲:
166. Fraction to Recurring Decimal

43. Multiply Strings
415. Add Strings

67. Add Binary(思路和模板与上一题相同)
371. Sum of Two Integers(用位操作来代替实际的加减)
下面两题思路一样(找到第一个非9的数,接着执行相应的操作):
66. Plus One
369. Plus One Linked List
注:链表加法的两道题目归为链表类

166. Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".

Given numerator = 2, denominator = 3, return "0.(6)".
思路:用一个hash table去记录从小数点开始的余数。因为两者都是整数,所以小数点之后都是0. 因为,如果从某个点开始重新遇到某个之前见过的余数(remainder)代表循环小数的部分出现了。
Extreme cases: 分子numerator是0, 分母dominator是0. 负数是Integer.MIN_VALUE的时候会溢出。
功能测试:两者其中之一或者两者是负数。两者是整数,结果是整数、结果是小数(有限或者无限)。public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder fraction = new StringBuilder();
// If either one is negative (not both)
if (numerator < 0 ^ denominator < 0) {
fraction.append("-");
}
// Convert to Long or else abs(-2147483648) overflows
long dividend = Math.abs(Long.valueOf(numerator));
long divisor = Math.abs(Long.valueOf(denominator));
fraction.append(String.valueOf(dividend / divisor));
long remainder = dividend % divisor;
if (remainder == 0) {
return fraction.toString();
}
fraction.append(".");
Map<Long, Integer> map = new HashMap<>();
while (remainder != 0) {
if (map.containsKey(remainder)) {
fraction.insert(map.get(remainder), "(");
fraction.append(")");
break;
}
map.put(remainder, fraction.length());
remainder *= 10;
fraction.append(String.valueOf(remainder / divisor));
remainder %= divisor;
}
return fraction.toString();
}
43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:两个数相乘得到的数字,比最多不会超过两个数的长度加起来的长度。例如(99 * 99 < 10000)
所以,StringBuilder的长度是这个长度。最后删除首部的0。接下来是正常的乘法,乘数每一位分别和被乘数的每一位相乘,用嵌套的for-loop即可实现。注意结果的坐标是i + j + 1,考虑到9 * 9或者1 * 1即可知。

public class Solution {
public String multiply(String num1, String num2) {
int n1 = num1.length(), n2 = num2.length();
int[] products = new int[n1 + n2];
for (int i = n1 - 1; i >= 0; i--) {
for (int j = n2 - 1; j >= 0; j--) {
int d1 = num1.charAt(i) - '0';
int d2 = num2.charAt(j) - '0';
products[i + j + 1] += d1 * d2;
}
}
int carry = 0;
for (int i = products.length - 1; i >= 0; i--) {
int tmp = (products[i] + carry) % 10;
carry = (products[i] + carry) / 10;
products[i] = tmp;
}
StringBuilder sb = new StringBuilder();
for (int num : products) sb.append(num);
while (sb.length() != 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);
return sb.length() == 0 ? "0" : sb.toString();
}
}

415. Add StringsGiven two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路:最长只会比两个数之间长度较长的那个数多一位。接下来就是普遍的加法需要注意的问题,carry必须最后检查一次并加上和while循环的时候记得递增或者递减变量。与链表加法的模板类似。

class Solution {
public String addStrings(String num1, String num2) {
int l1 = num1.length();
int l2 = num2.length();

int carry = 0;
int i = l1 - 1;
int j = l2 - 1;
int res = 0;

StringBuilder sb = new StringBuilder();
while (i >= 0 && j >= 0) {
res = (num1.charAt(i--) - '0') + (num2.charAt(j--) - '0') + carry;
carry = res / 10;
res = res % 10;
sb.append(Integer.toString(res));
}

while (i >= 0) {
res = (num1.charAt(i--) - '0') + carry;
carry = res / 10;
res = res % 10;
sb.append(Integer.toString(res));
}

while (j >= 0) {
res = (num2.charAt(j--) - '0') + carry;
carry = res / 10;
res = res % 10;
sb.append(Integer.toString(res));
}

if (carry > 0) {
sb.append(Integer.toString(carry));
carry = 0;
}

return sb.reverse().toString();
}
}

67. Add Binary
Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}

371. Sum of Two IntegersCalculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.

/**
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

a作为直接加的数,b作为进位,继续递归。
*/
class Solution {
public int getSum(int a, int b) {
if (b == 0) {
return a;
}
int newA = a ^ b;
int newB = (a & b) << 1;
return getSum(newA, newB);
}
}
369. Plus One Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode plusOne(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode lastNotNine = dummy, node = head;

while (node != null) {
if (node.val != 9) {
lastNotNine = node;
}
node = node.next;
}
lastNotNine.val++;
node = lastNotNine.next;
while (node != null) {
node.val = 0;
node = node.next;
}
return dummy.val == 1 ? dummy : dummy.next;
}
}
66. Plus Oneclass Solution {
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0) {
return digits;
}

int lastNotNine = -1;
for (int i = digits.length - 1; i >= 0; --i) {
if (digits[i] != 9) {
lastNotNine = i;
break;
}
}

if (lastNotNine == -1) {
int[] ans = new int[digits.length + 1];
ans[0] = 1;
return ans;
}

int zeroIndex = lastNotNine + 1;
while (zeroIndex != digits.length) {
digits[zeroIndex++] = 0;
}

digits[lastNotNine]++;
return digits;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: