package ygy.test.week5;
/**
* Created by guoyao on 2017/10/1.
*/publicclassAddBinary {publicstaticvoidmain(String[] args) {
System.out.println(addBinary("1","111"));
}
/**
* Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/publicstatic String addBinary(String a, String b) {
StringBuilder stringBuilder=new StringBuilder();
int z = 0 ;
int n=Math.max(a.length(), b.length());
for (int i = 0 ; i< n;i ++ ) {
int x = 0 ;
if ((a.length() - 1 - i) > -1) {
x=Integer.valueOf(a.substring(a.length() - 1 - i,a.length()- i));
}
int y= 0 ;
if ((b.length() - 1 - i) > -1) {
y =Integer.valueOf(b.substring(b.length() - 1 - i,b.length()- i));
}
if ((x + y + z) > 1) {
stringBuilder.append((x + y +z - 2));
z=1;
} else {
stringBuilder.append((x + y + z));
z=0;
}
}
if (z > 0) {
stringBuilder.append(z);
}
return stringBuilder.reverse().toString();
}
//leetcode answerpublic String addBinary_2(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();
}
}
Climbing Stairs
package ygy.test.week5;
/**
* Created by guoyao on 2017/10/2.
*/publicclassClimbingStairs {publicstaticvoidmain(String[] args) throws InterruptedException {
System.out.println(climbStairs(5));
}
/**
* You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
*/publicstaticintclimbStairs(int n) {
// 最后一步可以采用1步,也可以采用两步//所以可能性是原始的f(n-1) 和 f(n-2)之和//所以总数为两者之和if(n == 0 || n == 1 || n == 2){return n;}
int[] temp = newint[n];
temp[0] = 1;
temp[1] = 2;
for(int i = 2; i < n; i++){
temp[i] = temp[i-1] + temp[i-2];
}
return temp[n-1];
}
}
Length of Last Word
package ygy.test.week5;
/**
* Created by guoyao on 2017/10/1.
*/publicclassLengthofLastWord {publicstaticvoidmain(String[] args) {
System.out.println(lengthOfLastWord("hello "));
}
publicstaticintlengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
}
Sqrt
package ygy.test.week5;
/**
* Created by guoyao on 2017/10/2.
*/publicclassSqrt {publicstaticvoidmain(String[] args) {
System.out.println(mySqrt(2));
}
/**
* Implement int sqrt(int x).
Compute and return the square root of x.
*///leetcode答案publicstaticintmySqrt(int x) {
long r = x;
while (r*r > x)
r = (r + x/r) / 2;
return (int) r;
}
}
Add Binarypackage ygy.test.week5;/** * Created by guoyao on 2017/10/1. */public class AddBinary { public static void main(String[] args) { System.out.println(addBinary("1","111")); }