Update Solution.java
parent
27074cb4c6
commit
2628f99a31
|
|
@ -313,4 +313,93 @@ public class Solution {
|
||||||
|
|
||||||
return newNumber;
|
return newNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。
|
||||||
|
*
|
||||||
|
* 输入为 非空 字符串且只包含数字 1 和 0。
|
||||||
|
* @param a
|
||||||
|
* @param b
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String addBinary(String a, String b) {
|
||||||
|
StringBuilder result = new StringBuilder(); // 用于存储结果
|
||||||
|
int carry = 0; // 进位
|
||||||
|
int i = a.length() - 1, j = b.length() - 1; // 指向字符串a和b的最后一位
|
||||||
|
|
||||||
|
// 当i或j在范围内,或有进位时,继续循环
|
||||||
|
while (i >= 0 || j >= 0 || carry == 1) {
|
||||||
|
int sum = carry; // 当前位的和,初始为进位
|
||||||
|
|
||||||
|
// 如果i在范围内,加上a的当前位
|
||||||
|
if (i >= 0) {
|
||||||
|
sum += a.charAt(i) - '0'; // 将字符转换为数字
|
||||||
|
i--; // 移动到下一位
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果j在范围内,加上b的当前位
|
||||||
|
if (j >= 0) {
|
||||||
|
sum += b.charAt(j) - '0'; // 将字符转换为数字
|
||||||
|
j--; // 移动到下一位
|
||||||
|
}
|
||||||
|
|
||||||
|
result.append(sum % 2); // 当前位的结果
|
||||||
|
carry = sum / 2; // 更新进位
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.reverse().toString(); // 反转结果并返回
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
|
||||||
|
* 由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
|
||||||
|
* 注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
|
||||||
|
*
|
||||||
|
* @param x
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static int mySqrt(int x) {
|
||||||
|
if (x < 2){
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
long guess = x / 2;
|
||||||
|
while (guess * guess > x){
|
||||||
|
guess = (guess + x/guess)/2;
|
||||||
|
}
|
||||||
|
return (int) guess;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
|
||||||
|
* 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
|
||||||
|
* @param n
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static int climbStairs(int n) {
|
||||||
|
if(n < 3)return n;
|
||||||
|
int dp[]=new int[n+1];
|
||||||
|
dp[1]=1;
|
||||||
|
dp[2]=2;
|
||||||
|
for(int i=3;i<n+1;i++) {
|
||||||
|
dp[i]=dp[i-1]+dp[i-2];
|
||||||
|
}
|
||||||
|
return dp[n];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
|
||||||
|
* @param head
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static ListNode deleteDuplicates(ListNode head) {
|
||||||
|
ListNode current = head;
|
||||||
|
while (current!= null && current.next != null){
|
||||||
|
if (current.val == current.next.val){
|
||||||
|
current.next = current.next.next;
|
||||||
|
}else {
|
||||||
|
current = current.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue