Update Solution.java

master
wsy182 2024-07-09 21:53:30 +08:00
parent 27074cb4c6
commit 2628f99a31
1 changed files with 89 additions and 0 deletions

View File

@ -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;
}
} }