您的位置 首页 编程语言

decodeArray

美国程序员面试题

An integer number can be encoded as an array as follows. Each digit n of the number is represented by n zeros followed by a 1. So the digit 5 is represented by 0, 0, 0, 0, 0, 1. The encodings of each digit of a number are combined to form the encoding of the number. So the number 1234 is encoded as the array {0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1}. The first 0, 1 is contributed by the digit 1, the next 0, 0, 1 is contributed by the digit 2, and so on.
There is one other encoding rule: if the number is negative, the first element of the encoded array must be -1, so -201 is encoded as {-1, 0, 0, 1, 1, 0, 1}. Note that the 0 digit is represented by no zeros, i.e. there are two consecutive ones!
Write a method named decodeArray that takes an encoded array and decodes it to return the number.
You may assume that the input array is a legal encoded array, i.e., that -1 will only appear as the first element, all elements are either 0, 1 or -1 and that the last element is 1.
If you are programming in Java or C#, the function prototype is int decodeArray(int[ ] a)
If you are programming in C or C++, the function prototype is int decodeArray(int a[ ], int len);

花猫大叔

测试样例:

 

 

java 实现代码:

package com.zzy;

/**
 * 更多请关注: http://huamaodashu.com
 * Created by huamaodashu on 06/08/2018.
 */
public class ecodeArray {
    public static void main(String[] args) {

//        int[] a = {-1,0,0,1,1,0,1};
//        int[] a = {-1,0,1};
//        int[] a = {0, 1, 1, 1, 1, 1, 0, 1};
        int[] a = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1};
        System.out.println(decodeArray(a));
    }

    public static int decodeArray(int[] a){

    //assume的条件是否要检查
        int flag =0;
        int i =0;

        if(a[0] == -1){
            flag=1;
            i = 1;
        }
        int count = 0;
        int sum = 0;

        for ( ; i < a.length; i++) {

            if(a[i]==0){
                count++;
            }else if(a[i] == 1){

                sum = sum * 10 + count;
                count = 0;
            }
        }
        if(flag == 1){
            sum = -sum;
        }
        return sum;
    }
}

猫叔总结了 适合新手操作的副业 《淘宝虚拟产品月入2万的 6个 细分类目》的电子书 仅供参考

如果你对虚拟产品比较感兴趣,可以点击:

淘宝卖什么虚拟产品赚钱(月入2万+)

hadoopall

关于花猫大叔短视频创业 作者: hadoopall

热门文章

发表评论

电子邮件地址不会被公开。