提交网址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2729
题目:
Vivid has stored a piece of private information, which consisted of a serial of integers in a secret number format. All the stored numbers are in the range [-63, 63]. So every number contains exactly 7 bits - the leftmost bit is the sign bit (0 for positive and 1 for negative), and all other bits represent the absolute value of the number (e.g. 000000 stands for 0, 000001 stands for 1 and 111111 stands for 63). With the sign bit, 1000000 and 0000000 are considered to be equal, both of them stand for 0.
All the numbers have been pushed into 16-bits integers, that is, one 16-bits integer is enough to hold 2 numbers plus 2 bits of another number.
In this problem, you are given a serial of 16-bits integers, and you need to output the sum of these 7-bits integers.
Input:
There are multiple test cases. Each test case begins with an integer N (the number of 16-bits numbers, 0 <= N <= 7000, N is always a multiple of 7). Then N 16-bits numbers follow, all of which are in the range [0, 65535]. A case with N = -1 denotes the end of input, which should not be proceeded.
Output:
For each test case, output an integer indicating the sum of these 7bits-integers in a single line.
Sample Input:
7 1 0 0 0 0 0 0 7 65535 65535 65535 65535 65535 65535 65535 -1
Sample Output:
32 -1008
—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
题意:
本题意思大致为输入一个n,然后依次输入n个 在[0, 65535]范围内的16位数,然后在这些数转换位7位数求和。当n=-1时,程序结束。
分析:
此题较为简单只需要将读入的16位数存储起来然后再将其全部转换为二进制存储起来,然后每七位做一次运算即可。(需要注意符号位) 代码如下:
1 import java.util.Scanner; 2 3 public class Zoj2729 { 4 final static int MAX = 7001; 5 6 public static void main(String[] args) { 7 Scanner cin = new Scanner(System.in); 8 int n; 9 int t, temp, ans,sum; 10 //用于存放读取的16位数 11 int[] arr = new int[MAX]; 12 //用于存储将16位数转换为二进制的数组 13 int[] arr1 = new int[MAX * 17]; 14 15 while (cin.hasNext()) { 16 n = cin.nextInt(); 17 if(n==-1){ 18 break; 19 } 20 temp = 0; 21 ans=0; 22 sum=0; 23 //读取16位的数 24 for (int i = 0; i < n; i++) { 25 arr[i] = cin.nextInt(); 26 } 27 for (int i = n - 1; i >= 0; i--) { 28 t = 0; 29 //转换成16位二进制存放到数组内 30 while (t < 16) { 31 //位运算,相当于快速取模 32 arr1[temp++] = arr[i] & 1; 33 //左移一位相当于除2 34 arr[i] >>= 1; 35 t++; 36 } 37 } 38 for (int i = 1; i <= temp + 1; i++) { 39 //每七位二进制做一次运算 40 if (i % 7 != 0) { 41 ans += arr1[i - 1] << (i % 7 - 1); 42 } else { 43 if(arr1[i-1]!=0){//判断符号位,如果为1表示负数则减掉 44 sum-=ans; 45 }else{ 46 sum+=ans; 47 } 48 ans=0; 49 } 50 } 51 System.out.println(sum); 52 } 53 } 54 55 }
第一次写博客,如果写的不好也请多多见谅。
希望大家多多指教,共同进步。