@programeggsoup
2018-07-10T23:58:08.000000Z
字数 4440
阅读 1037
java python LintCode 计算机
Write a function that add two numbers A and B.
Given a=1 and b=2 return 3.
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
在计算机中,数字是以补码的形式存在的,计算也是用补码来进行计算,计算后的结果也是补码,可以参考图解 Java 位运算。
public class Solution {/*** @param a: An integer* @param b: An integer* @return: The sum of a and b*/public int aplusb(int a, int b) {// write your code hereif(b==0){return a;}int xor = a ^ b;int carry = (a & b) << 1;return aplusb(xor, carry);}}
- Reference: [不用加减乘除做加法.py][2]
- 因为python整形无限大,所以导致不能直接用java魔改,不然会很慢很慢很慢
- Total runtime: 302ms
class Solution:"""@param a: An integer@param b: An integer@return: The sum of a and b"""def aplusb(self, a, b):# write your code herewhile b != 0:xor = a ^ bb = (a & b) << 1a = xor & 0xFFFFFFFFreturn a if a >> 31 == 0 else a - 4294967296
Write an algorithm which computes the number of trailing zeros in n factorial.
11! = 39916800, so the out should be 2
O(log N) time
只有2和5碰在一起的时候,才会有0,而5的个数远比0少,只要计算有多少5
25/5 = 5,5/5 = 1;5+1=6
2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
class Solution:"""@param: n: An integer@return: An integer, denote the number of trailing zeros in n!"""def trailingZeros(self, n):# write your code here, try to do it without arithmetic operators.if n == 0:return 0count = 0while n > 0:n /= 5count += nreturn count
public class Solution {/** @param n: An integer* @return: An integer, denote the number of trailing zeros in n!*/public long trailingZeros(long n) {// write your code here, try to do it without arithmetic operators.if(n == 1) {return 0;}int five = 0; // 2出现的频率永远低于5,所以只要计算5就行了,一个5配一个2,才能有0for(long i = 5; n / i > 0; i *= 5) {//2,4,5,6,8,10,12,14,15,20five += n / i;}return five;}}
Merge two given sorted integer array A and B into a new sorted integer array.
A=[1,2,3,4]
B=[2,4,5,6]
return [1,2,2,3,4,4,5,6]
How can you optimize your algorithm if one array is very large and the other is very small?
public class Solution {/*** @param A: sorted integer array A* @param B: sorted integer array B* @return: A new sorted integer array*/public int[] mergeSortedArray(int[] A, int[] B) {// write your code hereint[] merge = new int[A.length + B.length];System.arraycopy(A,0, merge, 0, A.length);System.arraycopy(B, 0, merge, A.length, B.length);Arrays.sort(merge);return merge;}}
class Solution:"""@param A: sorted integer array A@param B: sorted integer array B@return: A new sorted integer array"""def mergeSortedArray(self, A, B):# write your code hereC = A + Blist.sort(C)return C
Given a string and an offset, rotate string by offset. (rotate from left to right)
Given "abcdefg".
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
Rotate in-place with O(1) extra memory.
public class Solution {/*** @param str: An array of char* @param offset: An integer* @return: nothing*/public void rotateString(char[] str, int offset) {// write your code hereif(offset != 0 && str.length != 0) {offset %= str.length;if(offset != 0) {char[] copy = str.clone();for (int i = 0; i < offset; i++) {str[i] = copy[str.length - offset + i];}for (int i = offset; i < str.length; i++) {str[i] = copy[i - offset];}}}}}
class Solution:"""@param str: An array of char@param offset: An integer@return: nothing"""def rotateString(self, str, offset):# write your code hereif len(str) != 0:offset %= len(str)if offset != 0:a = str[:-offset]b = str[-offset:]c = b + a#str.replace(b+a)for i, item in enumerate(str):str[i] = c[i]
Reverse a 3-digit integer.
Reverse 123 you will get 321.
Reverse 900 you will get 9.
Running time: 757 ms
public class Solution {/*** @param number: A 3-digit number.* @return: Reversed number.*/public int reverseInteger(int number) {// write your code hereStringBuilder str = new StringBuilder();str.append(number);str = str.reverse();String result = String.valueOf(str);if(result.substring(0,1).equals("0")){result = result.substring(1,result.length());}return Integer.parseInt(result);}}
Running Time = 252ms
class Solution:"""@param number: A 3-digit number.@return: Reversed number."""def reverseInteger(self, number):# write your code heretemp = str(number)temp = temp[::-1]if temp[:1] == "0":temp = temp[2:]return int(temp)
Convert a lowercase character to uppercase.
a -> A, b -> B ...
Total runtime 3955 ms
public class Solution {/*** @param character: a character* @return: a character*/public char lowercaseToUppercase(char character) {// write your code herereturn (char)(character - 'a' + 'A');}}
Total runtime 1310 ms
class Solution:"""@param character: a character@return: a character"""def lowercaseToUppercase(self, character):# write your code herereturn character.upper()