Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        4年前关闭。
                    
                
        

我得到的任务是总结一个数组的所有值,除了以6开头的部分,直到下一个7出现为止。 7之后的值将再次加到我的总和中。

这是我的解决方案之一:

        if(nums == null){
            return 0;
        }else if(nums.length == 0){
            return 0;
        }else{
            int sum = 0;
            int countTill7 = 0;
            boolean six = false;

            for(int i = 0; i < nums.length; i++){
                if(nums[i] != 6){
                    sum += nums[i];
                }else if(nums[i] == 6){
                    six = true;
                    countTill7++;
                }else if(six == true && nums[i - 1] == 7){
                    six = false;
                    sum += nums[i];
                }

            }

            return sum;
        }


我找不到问题..

最佳答案

这是我总结一个数组的所有值的方法,除了以6开头的部分,直到下一个7出现为止

package codingbat.array3;

public class Sum67
{
    public static void main(String[] args)
    {
    }

    /**
     * Return the sum of the numbers in the array,
     * except ignore sections of numbers starting with a 6 and
     * extending to the next 7
     * (every 6 will be followed by at least one 7).
     * Return 0 for no numbers.
     *
     * sum67({1, 2, 2}) → 5
     * sum67({1, 2, 2, 6, 99, 99, 7}) → 5
     * sum67({1, 1, 6, 7, 2}) → 4
     */
    public int sum67(int[] nums)
    {
        int sum = 0;
        boolean got6 = false;

        for (int i = 0; i < nums.length; i++)
        {
            if (6 == nums[i])
            {
                got6 = true;
            }
            else if (got6 && 7 == nums[i])
            {
                got6 = false;
            }
            else if (!got6)
            {
                sum += nums[i];
            }
        }

        return sum;
    }
}

关于java - Java-总结除特定部分外的Array值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35741768/

10-12 14:40