软考题

题目1:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。

  例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。

///////////////////////////////////////////////////////////////////////

  // Find two numbers with a sum in a sorted array

  // Output: ture is found such two numbers, otherwise false

  ///////////////////////////////////////////////////////////////////////

  bool FindTwoNumbersWithSum

  {

  int data[], // a sorted array

  unsigned int length, // the length of the sorted array

  int sum, // the sum

  int& num1, // the first number, output

  int& num2 // the second number, output

  bool found = false;

  if(length < 1)

  return found;

  int ahead = length - 1;

  int behind = 0;

  while(ahead > behind)

  {

  long long curSum = data[ahead] + data[behind];

  // if the sum of two numbers is equal to the input

  // we have found them

  if(curSum == sum)

  {

  num1 = data[behind];

  num2 = data[ahead];

  found = true;

  break;

  }

  // if the sum of two numbers is greater than the input

  // decrease the greater number

  else if(curSum > sum)

  ahead --;

  // if the sum of two numbers is less than the input

  // increase the less number

  else

  behind ++;

  }

  return found;

  }

 

题目2:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。

  例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。

int NumberOf1(unsigned int n);

  /////////////////////////////////////////////////////////////////////////////

  // Find the number of 1 in the integers between 1 and n

  // Input: n - an integer

  // Output: the number of 1 in the integers between 1 and n

  /////////////////////////////////////////////////////////////////////////////

  int NumberOf1BeforeBetween1AndN_Solution1(unsigned int n)

  {

  int number = 0;

  // Find the number of 1 in each integer between 1 and n

  for(unsigned int i = 1; i <= n; ++ i)

  number += NumberOf1(i);

  return number;

  }

  /////////////////////////////////////////////////////////////////////////////

  // Find the number of 1 in an integer with radix 10

  // Input: n - an integer

  // Output: the number of 1 in n with radix

  /////////////////////////////////////////////////////////////////////////////

  int NumberOf1(unsigned int n)

  {

  int number = 0;

  while(n)

  {

  if(n % 10 == 1)

  number ++;

  n = n / 10;

  }

  return number;

  }

 

posted @ 2016-05-09 15:58  二哥(阿伟)  阅读(222)  评论(0编辑  收藏  举报