Compare commits

...

2 Commits

Author SHA1 Message Date
5d29f810a2 Update test.java 2024-07-09 21:53:33 +08:00
2628f99a31 Update Solution.java 2024-07-09 21:53:30 +08:00
2 changed files with 95 additions and 3 deletions

View File

@@ -313,4 +313,93 @@ public class Solution {
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;
}
}

View File

@@ -6,9 +6,12 @@ import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
int[] nums = new int[]{9};
int[] result = Solution.plusOne(nums);
ListNode head = new ListNode(1);
head.next = new ListNode(1);
head.next.next = new ListNode(1);
head.next.next.next = new ListNode(2);
ListNode result = Solution.deleteDuplicates(head);
System.out.println(result.toString());
}
}