用C#语言编写程序 [英] program in c# language

查看:124
本文介绍了用C#语言编写程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我编写以下程序:

编写一个带有信号布尔值sumIsPower(int [] arr)的函数sumIsPower,如果输入数组arr中元素的总和为2的幂,则输出true,否则返回false.回想一下2的幂是1、2、4、8、16,?;通常,当且仅当对于某些非负整数n而言,数字的形式为2 ^ n时,数字是2的幂.您可以假设(无需在代码中进行验证)数组中的所有元素都是正整数.如果输入arr为null或长度为0,则返回值应为false.注意:x ^ n表示x等于n的幂.

please help me write this program:

Write a function sumIsPower with signatuare boolean sumIsPower(int[] arr) which outputs true if the sum of the elements in the input array arr is a power of 2, false otherwise. Recall that the powers of 2 are 1, 2, 4, 8, 16, ?; in general a number is a power of 2 if and only if it is of the form 2^n for some nonnegative integer n. You may assume (without verifying in your code) that all elements in the array are positive integers. If the input arr is null or of length 0, the return value should be false. Note: x^n means x to the power of n.

推荐答案

当人们如此懒惰以至于无法打扰时,我通常不会咬人向Google咨询什么是广泛讨论的主题 [ ^ ]

I don''t normally bite when people are so lazy they can''t even be bothered to Google for what is a widely discussed subject[^]

public bool sumIsPower(int[] arr)
{
    if (arr == null || arr.Length == 0)
        return false;

    int total = 0;
    for (int i = 0; i < arr.Length; ++i)
        total += arr[i];

    return (total != 0) && ((total & (total - 1)) == 0); 
} 



...认为应该这样做-最近不得不用铅笔将其中之一写出来进行面试!



...think that should do it tho - had to write one of these out with a pencil for a job interview recently!


这并不困难-但这是一项测试,您真的应该自己做这项工作!所以,没有代码.

很简单:
0)检查他们提到的错误情况.
1)遍历输入中的每个元素,将它们添加在一起.您可能要检测溢出并报告问题.
2)检查结果:确定它是否为2的幂.有很多方法可以做到这一点,有两种:
2.1)循环求和,然后将其与单个移动位1、2、4、8、16,...进行比较,如果匹配,则为2的幂.
2.2)计算数字中的"1"位.如果为1,则为2的幂.还有很多方法可以做到这一点-MIT HAKEM备忘录提供了一种可爱的无循环方法!
It''s not difficult - but since this is a test, you really should do the work yourself! So, no code.

It''s pretty easy:
0) Check the error conditions they mentioned.
1) Loop though each element in the input, adding them together. You might want to detect overflow and report a problem.
2) Examine the result: deciding if it is a power of two. There are a lot of ways to do this, here are two:
2.1) Loop though the sum, comparing it with a single moving bit 1, 2, 4, 8, 16, ... If you get a match it''s a power of two.
2.2) Count the ''1'' bits in the number. If it is one, then it''s a power of two. There are a lot of ways to do that, as well - the MIT HAKEM memo provides a lovely no-loop way to do it!


这篇关于用C#语言编写程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆