您的位置 首页 编程语言

checkContenatedSum

美国程序员面试题

 

The number 198 has the property that 198 = 11 + 99 + 88, i.e., if each of its digits is concatenated twice and then summed, the result will be the original number. It turns out that 198 is the only number with this property. However, the property can be generalized so that each digit is concatenated n times and then summed. For example, 2997 = 222+999+999+777 and here each digit is concatenated three times. Write a function named checkContenatedSum that tests if a number has this generalized property.
The signature of the function is
int checkConcatenatedSum(int n, int catlen) where n is the number and catlen is the number of times to concatenate each digit before summing.
The function returns 1 if n is equal to the sum of each of its digits contenated catlen times. Otherwise, it returns 0. You may assume that n and catlen are greater than zero
Hint: Use integer and modulo 10 arithmetic to sequence through the digits of the argument.

 

测试样例:

 

java代码实现

 

package com.zzy;

/**
 * 更多请关注: http://huamaodashu.com
 * Created by huamaodashu on 24/07/2018.
 */
public class checkConcatenatedSum {
    public static void main(String[] args) {
        System.out.println(checkConcatenatedSum(9, 1));
        System.out.println();

    }
    public static int checkConcatenatedSum(int n, int catlen){

        int tmp = n;
        int sum =0;
        while (true){


            sum= sum+ numbs(n%10,catlen);

//            System.out.println("sum1="+sum);
            n=n/10;
            if(n==0){
                break;
            }

        }

        if(tmp == sum){
            return 1;
        }
//        System.out.println("sum"+sum);
        return 0;

    }

    public static int numbs(int a,int n){
        int sum = a;
        for (int i = 1; i < n; i++) {
            sum=sum+a*(int)Math.pow(10,i);
        }

//        System.out.println(sum);
        return sum;
    }
}

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

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

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

hadoopall

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

热门文章

发表评论

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