- Length of last word (*)
Trim () : trim() If no space is found, there is only one word. Return the length of s directly. If found, return s.length() -1 -i which is the length of the last word
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int i = s.length() - 1;
while (i >= 0&& s.charAt(i) ! =' ')
i--;
if (i == -1) {
return s.length();
} else {
return s.length() - 1- i; }}}Copy the code
- Gal.
We use a variable jinwei to represent the carry of the previous position. The initial value is 1. The result bit of each bit is a[I]+ B [j]+ Jinwei mod 10, and the carry of the next bit is a[I]+ B [j]+ Jinwei /10. If digits[0] equals 0 after the end, open up a new array and set the first digit to 1.
class Solution {
public int[] plusOne(int[] digits) {
int temp;
int jinwei = 1;
for (int i = digits.length - 1; i >= 0; i--) {
temp = (digits[i] + jinwei) % 10;
jinwei = (digits[i] + jinwei) / 10;
digits[i] = temp;
}
if (digits[0] = =0) {
int a[] = new int[digits.length + 1];
a[0] = 1;
for (int i = 1; i < a.length; i++) {
a[i] = 0;
}
return a;
} else {
returndigits; }}}Copy the code
- Binary sum (*)
We use a variable jinwei to represent the carry of the previous position. The initial value is 0. The result bit of each bit is a[I]+b[j]+ Jinwei mod 2, and the carry of the next bit is A [I]+b[j]+ Jinwei /2. The resulting bits are continuously added to the string, finally inverted. My solution:
class Solution {
public String addBinary(String a, String b) {
int temp;
int jinwei = 0;
String s = "";
String result = "";
int i = a.length() - 1, j = b.length() - 1;
while (i >= 0 && j >= 0) {
temp = ((a.charAt(i)-'0') + (b.charAt(j)-'0') + jinwei) % 2;//char- '0' can be changed to a number
jinwei = ((a.charAt(i)-'0') + (b.charAt(j)-'0') + jinwei) / 2;
s += temp;
i--;
j--;
}
if (i == -1) {
while (j >= 0) {
temp = (b.charAt(j) - '0' + jinwei) % 2;
jinwei = (b.charAt(j) - '0' + jinwei) / 2;
s += temp;
j--;
}
if(jinwei ! =0) {
s += 1;
jinwei = 0; }}if (j == -1) {
while (i >= 0) {
temp = (a.charAt(i) - '0' + jinwei) % 2;
jinwei = (a.charAt(i) - '0' + jinwei) / 2;
s += temp;
i--;
}
if(jinwei ! =0) {
s += 1; }}for (int k = s.length() - 1; k >= 0; k--) {
result += s.charAt(k);
}
returnresult; }}Copy the code
Official solution: The official solution uses a variable I, starting with the longest binary string. Then add each bit of the two binary strings back and forth to find the remainder. The characteristic of this method is to treat the fewer bits of a string with fewer bits as zeros
class Solution { public String addBinary(String a, String b) { StringBuffer ans = new StringBuffer(); int n = Math.max(a.length(), b.length()), carry = 0; for (int i = 0; i < n; ++i) { carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0; carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0; ans.append((char) (carry % 2 + '0')); carry /= 2; } if (carry > 0) { ans.append('1'); } ans.reverse(); return ans.toString(); }}Copy the code