Hawstein's Blog

Make something people love

Cracking the coding interview--Q5.6

题目 原文: Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc). 译文: 写程序交换一个整数二进制表示中的...

Cracking the coding interview--Q5.5

题目 原文: Write a function to determine the number of bits required to convert integer A to integer B. Input: 31, 14 Output: 2 译文: 写程序计算从整数A变为整数B需要修改的二进制位数。 输入:31,14 输出:2 解答 这道题目也比较简单,从整数A变...

Cracking the coding interview--Q5.4

题目 原文: Explain what the following code does: ((n & (n-1)) == 0). 译文: 解答以下代码的作用:((n & (n-1)) == 0) 解答 这个比较简单,代码的作用是判断一个数是否为2的整数次幂。题目中的判断代码不够严谨, 因为当n=0时,上述条件为真,但0并不是2的幂。所以,上述语句可以修改为: 1...

Cracking the coding interview--Q5.3

题目 原文: Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation. 译文: 给定一个整数x,找出另外两个整数,这两个整数的二进制表示中1的个数和x相同, 其中一个是比x大...

C/C++字符串处理

前言 字符串处理是编程中常遇到的问题,这时候如果能熟练地运用C/C++已有的字符串处理函数, 将大大地提高编程效率。 C++ Strings 需要包含头文件<string>,即#include <string>,以下是一些常用函数。 append:在字符串后面追加 1 2 3 4 5 6 7 8 string s1 = "hello ", s2 = ...

Cracking the coding interview--Q5.2

题目 原文: Given a (decimal - e.g. 3.72) number that is passed in as a string, print the binary representation.If the number can not be represented accurately in binary, print “ERROR”. 译文: 给定一个字符...

Cracking the coding interview--Q5.1

题目 原文: You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i a...

Cracking the coding interview--Q4.8

题目 原文: You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not...

Cracking the coding interview--Q4.7

题目 原文: You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 译文: 有两棵很大的二叉树:T1有上百万个结点,T2有上百个结...

Cracking the coding interview--Q4.6

题目 原文: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a bi...